🎓 A1Learner
🔍
0 of 50 lessons completed

Flask JSON Requests

A JSON request sends its data as JSON text. request.get_json reads the data into a dict.

Make the app

This line imports Flask and request together. The route below reads JSON.

from flask import Flask, request

app = Flask(__name__)

Add two JSON numbers

The view reads the JSON body into a dict. It adds the two numbers and returns the sum as text.

@app.route("/total", methods=["POST"])
def total():
    data = request.get_json()
    return str(data["a"] + data["b"])

Post two JSON bodies

The test client posts JSON with json={...}. Each print shows the sum for that body.

client = app.test_client()
print(client.post("/total", json={"a": 3, "b": 4}).data.decode())
print(client.post("/total", json={"a": 10, "b": 5}).data.decode())

Example

from flask import Flask, request

app = Flask(__name__)

@app.route("/total", methods=["POST"])
def total():
    data = request.get_json()
    return str(data["a"] + data["b"])

client = app.test_client()
print(client.post("/total", json={"a": 3, "b": 4}).data.decode())
print(client.post("/total", json={"a": 10, "b": 5}).data.decode())

Key points

  • JSON is a text format for data, like a Python dict.
  • request.get_json() turns the JSON body into a dict.
  • The test client sends JSON with json={...}.
  • Use JSON when another program talks to the app.

In this example, the route takes POST only and reads the JSON body with get_json. The test client posts two JSON bodies. The prints show the sum for each body: 7 and 15.

Note

get_json needs the request to carry JSON.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does request.get_json() return for a JSON body {"a": 3, "b": 4}?