Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask: Cannot Decode Incoming JSON Submitted Using Requests

I'm having an issue trying to decode a python dictionary sent to my server as json. This is what I have in my application:

payload = {'status':[bathroomId,item,percentage,timestamp]}
r=requests.post(url,None,json.dumps(payload))

Here is what I do in my Flask server:

req = request.get_json()
print req['status']

When I try to print the content of req['status'], it seems like python won't recognize it as a dictionary and I get an internal server error.

I tried printing req, and I get None

What am I missing?

like image 993
Alessandro Gaballo Avatar asked Nov 18 '25 08:11

Alessandro Gaballo


1 Answers

Unless you set the Content-Type header to application/json in your request, Flask will not attempt to decode any JSON found in your request body.

Instead, get_json will return None (which is what you're seeing right now).

So, you need to set the Content-Type header in your request.

Fortunately since version 2.4.2 (released a year ago), requests has a helper argument to post JSON; this will set the proper headers for you. Use:

requests.post(url, json=payload)

Alternatively (e.g. using requests < 2.4.2), you can set the header yourself:

requests.post(url, data=json.dumps(payload), headers={"Content-Type": "application/json"})

Here is the relevant code from Flask:

  • Flask only loads JSON if is_json is True (or if you pass force=True to get_json). Otherwise, it returns None.
  • is_json looks at the Content-Type header, and looks for application/json there.
like image 196
Thomas Orozco Avatar answered Nov 19 '25 23:11

Thomas Orozco



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!