Flask 101: Add JSON to your Python Web App

Welcome to part two of the the Flask 101 Series. 

 

  1. Flask 101: Create a Basic Python Web App
  2. Flask 101: Add JSON to your Python Web App – This tutorial
  3. Flask 101: Use HTML templates & send variables 
  4. Flask 101: Serve Images 
  5. Flask 101: Serve CSV Files

To turn a Python dictionary into JSON format that you can return in your app, you can just use Flask’s jsonify() method. For this tutorial, we will use the same setup as in the first tutorial, except we are going to send JSON responses.

 

1 – Setup

If you want to use a Python 3 virtual environment, you can follow this post for example. But all you really need is to install Flask

# Install flask
pip install flask

 

2 – Create your basic flask application

We are going to create two routes to test our API

  • /
    Which is going to tell users how to use the api
  • add
    takes two numbers x and y and returns the value x+y

Create a file named myapp.py with the following contents. This time, we will return JSON results in the add() function.

from flask import Flask, request
from flask import jsonify

app = Flask(__name__)

@app.route('/')
def myapp():
    message = "To use this app: %s/add?x=value&y=value" % request.base_url
    return message

@app.route('/add')
def add():
    # Checking that both parameters have been supplied
    for param in ['x', 'y']:
        if not param in request.args:
            result = { 
                'type': '%s value is missing' % param, 
                'content': '', 
                'status': 'REQUEST_DENIED'
            }
            return jsonify(result)
    
    # Make sure they are numbers too
    try:
        x = float(request.args['x'])
        y = float(request.args['y'])
    except:
        return "x and y should be numbers"
    
    result = { 
        'type': 'result', 
        'content': x+y, 
        'status': 'REQUEST_OK'
    }   
    return jsonify(result)

 

3 – Run your app

In the same directory as myapp.py, create a file named runapp.sh with the following contents.

export FLASK_APP=myapp
export FLASK_ENV=development
flask run

Close the file, then in the command line, run it with

# Execute this in the command line inside the same directory 
bash runapp.sh

You should see the following output

* Serving Flask app "myapp" (lazy loading)
* Environment: development
* Debug mode: on
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
* Debugger PIN: 319-407-766

 

4 – Test your app