Search code examples
pythonflaskpython-requestsflask-restful

Self-built flask_restful api returns NULL when posted using request module


I have been teaching myself APIs lately, and just when I thought I had started to figure it out, I have run into this problem:

I have built my own api, using flast_restful:

from flask import Flask, request
from flask_restful import Resource, Api

app = Flask(__name__)
api = Api(app)


class HelloWorld(Resource):
    def get(self):
        return {"hello": "world"}

    def post(self):
        json_str = request.get_json()
        return {"you sent": json_str}


api.add_resource(HelloWorld, "/")

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

I am running it in the console, then planned to access it in-code, using the python requests module:

import requests

data = {"hello:": "world"}

r = requests.post("http://127.0.0.1:5000", data=data)

print(r.text)

Why does this return {"you sent": null}, instead of the data specified in the post request? Get requests work, and the response code of the post request is 200.

I assume there is some easy fix for this that I am simply not able to find. Any help much appreciated!


Solution

  • r = requests.post("http://127.0.0.1:5000", data=data)
    

    The problem here is data isn't being sent as json; it's form-encoded by default. To send it properly you have to set the content type as application/json in the header. You can do that like this:

    import json
    headers = {'Content-type': 'application/json'}
    r = requests.post("http://127.0.0.1:5000", data=json.dumps(data), headers=headers)
    

    or more simply like this with Requests version 2.4.2 and onward:

    r = requests.post("http://127.0.0.1:5000", json=data)