Flask: Parsing JSON data

The objective of this post is to explain how to parse and use JSON data from a POST request in Flask.


Introduction

The objective of this post is to explain how to parse and use JSON data from a POST request in Flask, a micro web framework for Python.

You can check an introduction to Flask here. More posts on Flask are listed in the “Related posts” section.


The code

First of all, we need to import the Flask class from the flask module, so all the functionality we need becomes available. We will also import the request object from the flask module, which we will use later.

Then, we create an instance of the Flask class. In the constructor, we pass the name of the module of our application, using the __name__ global variable.

from flask import Flask
from flask import request

app = Flask(__name__)

We will assume that the client will be posting JSON data, so we will specify a route that only answers to HTTP POST requests. Any GET request to the same URL will be ignored.

To do so, we specify the POST keyword to the methods argument of the route decorator. You can read more on how to control the HTTP allowed methods in this previous post. You can check the code bellow, which only has the route decorator and the declaration of the handling function.

@app.route('/postjson', methods = ['POST'])
def postJsonHandler():

Note that, in the previous code, we specified that the server will be listening on the /postjson URL.

First, to confirm if the content is of type JSON, we check the is_json attribute of the request object. This attribute indicates if this request is JSON or not [1].

To get the posted JSON data, we just need to call the get_json method on the request object, which parses the incoming JSON request data and returns it [2] as a Python dictionary.

You can check the full code bellow, which already includes the calling of the run method on the app object, to start the server. Note that we specified port 8090 for our server to be listening on.

from flask import Flask
from flask import request

app = Flask(__name__)

@app.route('/postjson', methods = ['POST'])
def postJsonHandler():
    print (request.is_json)
    content = request.get_json()
    print (content)
    return 'JSON posted'

app.run(host='0.0.0.0', port= 8090)

 


Testing the code

We can test this code by using Postman, which allows us to do POST requests very easily. After installing this Chrome extension, open it and, on the request tab, select the POST method from the dropdown.

On the URL, use 127.0.0.1:8090/postjson. So, we are using our machine’s loopback IP and the 8090 port we specified in the Python code. Then, click in the Body separator, so we can specify our JSON content.

All the relevant areas mentioned before are highlighted in figure 1.

postman-post-json

Figure 1 – Preparing the POST request in POSTMAN.

On the Body separator, choose the radio button raw.  A text editor should become available. On the dropdown next to the radio buttons, choose JSON (application/json) and then input valid JSON on the text editor, as indicated in figure 2.

POSTMAN body of JSON request.png

Figure 2 – Defining the JSON data to post.

You can use other JSON content, but bellow there is the one used in this example.

{ 
 "device":"TemperatureSensor", 
 "value":"20", 
 "timestamp":"25/01/2017 10:10:05" 
}

Finally, hit send and the POST request should be sent to the Flask server. You should get an output similar to the one in figure 3 if you are running the code on IDLE, the Python default IDE.

flask-json-parse

Figure 3 – Output of the test program in IDLE.

The “True” is the value of the is_json attribute, which indicates that the content was JSON. The string corresponds to our JSON content, sent from POSTMAN.

Note that we are printing the whole content from the dictionary that corresponds to the parsed JSON content. You can print each attribute of the JSON object by accessing the dictionary by the name of the attribute, as shown bellow.

print (content['device'])
print (content['value'])
print (content['timestamp'])


Related posts

 

References

[1] http://flask.pocoo.org/docs/0.12/api/#flask.Request.is_json

[2] http://flask.pocoo.org/docs/0.12/api/#flask.Request.get_json


Technical details

  • Python version:3.6.0
  • Flask library: 0.12
Advertisements
This entry was posted in Python and tagged , , , , , , , . Bookmark the permalink.

4 Responses to Flask: Parsing JSON data

  1. I might try this later 😎😎

    Liked by 1 person

  2. Pingback: ESP8266: Posting JSON data to a Flask server on the cloud | techtutorialsx

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s