By | August 11, 2018

JSON is a common format for sending data to and from a RESTful API. In this post we’ll see how we can allow a simple Flask API to receive a JSON input. This post extends my previous post which made a simple Flask RESTful API and uses the Flask ‘get_json()’ method to accept JSON input.

If you just want to get stuck in and have a go, you can check out this code on GitHub and get started. (I’m using a docker-ised version of flask, but you can use the information in this for any Flask app.)

How To Accept JSON Input

The basic unit we will use is request.get_json(). This is a method available within the Flask framework and allows the app to handle JSON input. (‘request’ is an object created as part of the flask ‘route’ decorator.)

We will use ‘get_json()’ to return a dictionary, like this:

json_dictionary = requests.get_json()

GET Request With JSON

The following is an example of how get_json can be incorporated into to a ‘GET’ request.  ‘request.get_json()’ returns a dictionary, which we can then handle as normal.

@app.route("/api/v1/resources/books/json", methods=['GET'])
def api_filter_json():
    books = request.get_json()
    results = []
    for book in books['books']:
        to_filter = []

        id = book['id']
        published = book['published']
        author = book['author']
        query = build_select_books_query(author, id, published, to_filter)

        conn = sqlite.connect('../data/books.db')
        conn.row_factory = dict_factory
        cur = conn.cursor()

        results.append(cur.execute(query, to_filter).fetchall()[0])

    return jsonify(results)

Other Request Types

The basic ‘request.get_json()’ approach can also be applied to other HTTP protocol request types such as POST or PUT. The application itself handles what it does with the JSON input it has received. Read more about different RESTful request types.

Testing the API

Once you have added get_json to your api you will want to test it. This is more involved than a simple url-based request as we need to somehow send json as part of the request.

To do this we will use ‘curl‘, but other approaches are possible.

curl --header "Content-Type: application/json" -X GET -d "{"books":[{"id":null,"author":"Ann Leckie ","""published""":2014},{"""id""":null,"""author""":"""John Scalzi""","""published""":2013}]}""

If you are using windows, you will need to escape the quotation marks in your JSON, and put the whole string in quotation marks. For example:

curl --header "Content-Type: application/json" -X GET -d ""{"""books""":[{"""id""":null,"""author""":"""Ann Leckie ""","""published""":2014},{"""id""":null,"""author""":"""John Scalzi""","""published""":2013}]}""