Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask request and application/json content type

I have a flask app with the following view:

@menus.route('/', methods=["PUT", "POST"]) def new():     return jsonify(request.json) 

However, this only works if the request's content type is set to application/json, otherwise the dict request.json is None.

I know that request.data has the request body as a string, but I don't want to be parsing it to a dict everytime a client forgets to set the request's content-type.

Is there a way to assume that every incoming request's content-type is application/json? All I want is to always have access to a valid request.json dict, even if the client forgets to set the application content-type to json.

like image 771
danielrvt Avatar asked Jan 01 '13 17:01

danielrvt


People also ask

How do I get JSON data from request body in Flask?

You need to set the request content type to application/json for the . json property and . get_json() method (with no arguments) to work as either will produce None otherwise.

How do you change the content type on a Flask?

To set content type with Python Flask, we can create a Response instance with the mimetype argument. to create the ajax view that returns a response by creating a Response instance with the mimetyp set to 'text/xml' to return an XML response with the xml string as the body.

How do you process incoming request data in Flask?

To access the incoming data in Flask, you have to use the request object. The request object holds all incoming data from the request, which includes the mimetype, referrer, IP address, raw data, HTTP method, and headers, among other things.


1 Answers

Use request.get_json() and set force to True:

@menus.route('/', methods=["PUT", "POST"]) def new():     return jsonify(request.get_json(force=True)) 

From the documentation:

By default this function will only load the json data if the mimetype is application/json but this can be overridden by the force parameter.

Parameters:

  • force – if set to True the mimetype is ignored.

For older Flask versions, < 0.10, if you want to be forgiving and allow for JSON, always, you can do the decode yourself, explicitly:

from flask import json  @menus.route('/', methods=["PUT", "POST"]) def new():     return jsonify(json.loads(request.data)) 
like image 64
Martijn Pieters Avatar answered Sep 28 '22 08:09

Martijn Pieters