Elcid_91
Elcid_91

Reputation: 1681

Trouble with Flask_restful and POST

Attempting to explore Flask_Restful with Marshmallow. I have the following code in my main .py:

from flask import Flask
from flask_restful import Api

app = Flask(__name__)
api = Api(app)
    
from hw import HelloWorld
api.add_resource(HelloWorld,"/users")

if __name__ == "__main__":
    app.run(debug=True)

hw.py:

from flask_restful import Resource,request
from marshmallow import Schema,fields

class UserSchema(Schema):
    recordid = fields.Str()
    lastname = fields.Str(required=True)
    firsname = fields.Str(required=True)

class HelloWorld(Resource):
    def post(self):
        print(request.form)
        schema = UserSchema()
        form = request.form
        return {
            "recordid": form["recordid"],
            "firstname": form["firstname"],
            "lastname": form["lastname"]
        }

my curl command:

curl http://localhost:5000/users -H "Content-Type: application/json" -d "{'recordid':'1','firstname':'Shawn','lastname':'Simmons'}"

the request.form object and request.json object are both empty when evaluating in the post method of HellowWorld:

ImmutableMultiDict([])

How do I get around this? Am I not coding something correctly?

Upvotes: 0

Views: 68

Answers (1)

Matteo Pasini
Matteo Pasini

Reputation: 2022

This is because you are trying to read the parameters passed in the body of the request: request.form. Use json_content = request.get_json() to get json params.

Upvotes: 2

Related Questions