Home > database >  How can I successfully call this endpoint?
How can I successfully call this endpoint?

Time:04-12

I am following a tutorial for a RESTful Flask API (https://www.rahmanfadhil.com/flask-rest-api/) and it says to send a request to something. I tried making a request with Postman but it says Content-Type is not application/json. The code is

from flask import Flask, request
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
from flask_restful import Api, Resource

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
db = SQLAlchemy(app)
ma = Marshmallow(app)
api = Api(app)


# classes
class Post(db.Model):
    post_id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(50))
    content = db.Column(db.String(255))

    def __repr__(self):
        return '<Post %s>' % self.title


class PostSchema(ma.Schema):
    class Meta:
        fields = ("post_id", "title", "content")
        model = Post


post_schema = PostSchema()
posts_schema = PostSchema(many=True)


class PostListResource(Resource):
    def get(self):
        posts = Post.query.all()
        return posts_schema.dump(posts)

    def post(self):
        new_post = Post(
            title=request.json['title'],
            content=request.json['content']
        )
        db.session.add(new_post)
        db.session.commit()
        return post_schema.dump(new_post)


api.add_resource(PostListResource, '/posts')


class PostResource(Resource):
    def get(self, post_id):
        post = Post.query.get_or_404(post_id)
        return post_schema.dump(post)

api.add_resource(PostResource, '/posts/<int:post_id>')

The tutorial says to run

$ curl http://localhost:5000/posts \
    -X POST \
    -H "Content-Type: application/json" \
    -d '{"title":"Post 1", "content":"Lorem ipsum"}'

which I did in Powershell but that returns an error:

Invoke-WebRequest : Cannot bind parameter 'Headers'. Cannot convert the "Content-Type: application/json" value of type       "System.String" to type "System.Collections.IDictionary".                                                                    At line:1 char:45                                                                                                              ... alhost:5000/posts -X POST -H "Content-Type: application/json" -d '{"t ...                                                                                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~                                                                CategoryInfo          : InvalidArgument: (:) [Invoke-WebRequest], ParameterBindingException                                  FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.InvokeWebRequestCommand 

Can you help? Thanks!

In addition, I would like to know how to call this from another program. What do I put in the requests API?

CodePudding user response:

Postman has a content type field in the Headers, make sure it is set to JSON

Content-Type application/json

you can also set this in the Body tab, but Postman will let you know if there is a mismatch. Make sure you select "raw" and paste the following into the window below:

{
    "title":"Post 1", 
    "content":"Lorem ipsum"
}

CodePudding user response:

This should work but I don't have a POST endpoint available to me so I can't test:

$Body = @{
    Title= "Post 1"
    Content = "Lorem ipsum"
}

Invoke-RestMethod -Uri "http://localhost:5000/posts" -Method Post -Body ($Body | ConvertTo-Json)
  • Related