Using JSON

Let's modify our simple example to return JSON instead of a web page:

from flask import Flask, jsonify

...
@app.route("/")
def index():
data = {
"cats": 5,
"people": 8,
"dogs": 4
}

return jsonify(data)

...

Flask comes with a module called jsonify, which translates a dictionary into JSON and returns it as the response. This makes handling JSON data very easy.

In this example, we create a dictionary with some example values. In a proper application, this could instead be data which has been pulled from a database and manipulated in some way.

This data is then passed to the jsonify function and given to the requesting application in JSON format.

Make sure your web server is running (run python3 server.py if it isn't), then open up a web browser and go over to http://127.0.0.1:5000 again. This time, you should see your response laid out differently. The exact format will depend on the web browser you are using. This screenshot shows how the response looks in Firefox version 60:

So, now that we have JSON coming from our web service, how do we use it in practice?

This question leads us nicely to the next topic—the requests module.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset