I'm sending a POST request to my Flask app with Postman and also the requests library. When I use Postman, I can get the data with json.loads(request.data)
. When I use requests or curl, I can get the data with request.form
. Why does sending the same data with the two tools populating different attributes?
You've used Postman to send the data as JSON, and you've used requests and curl to send it as form data. You can tell either program to send the data as whatever you expect, rather than letting it use its "default". For example, you can send JSON with requests:
import requests
requests.post('http://example.com/', json={'hello': 'world'})
Also note that you can get the JSON directly from the Flask request, without loading it yourself:
from flask import request
data = request.get_json()
request.data
holds the body of the request, whatever format it may be. Common types are application/json
and application/x-www-form-urlencoded
. If the content type was form-urlencoded
, then request.form
will be populated with the parsed data. If it was json
, then request.get_json()
will access it instead.
If you're really not sure if you'll get the data as a form or as JSON, you could write a short function to try to use one and if that doesn't work use the other.
def form_or_json():
data = request.get_json(silent=True)
return data if data is not None else request.form
# in a view
data = form_or_json()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With