Posting to Flask with Postman versus requests populates different request attributes Posting to Flask with Postman versus requests populates different request attributes flask flask

Posting to Flask with Postman versus requests populates different request 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 requestsrequests.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 requestdata = 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 viewdata = form_or_json()


I hope this quote from http://werkzeug.pocoo.org/docs/0.10/wrappers/#werkzeug.wrappers.Request explains it:

data A descriptor that calls get_data() and set_data(). This should not be used and will eventually get deprecated.