🎓 A1Learner
🔍
0 of 50 lessons completed

Building a Flask JSON API

A JSON API serves data to other programs. Each route answers with JSON instead of a page.

Make the app

This line imports Flask, request, and jsonify together. The list below holds the notes.

from flask import Flask, request, jsonify

app = Flask(__name__)

notes = []

List the notes

This route returns the whole notes list as JSON.

@app.route("/api/notes")
def list_notes():
    return jsonify(notes)

Add a note

This route reads the JSON body, adds the note to the list, and returns the note with 201.

@app.route("/api/notes", methods=["POST"])
def add_note():
    note = request.get_json()
    notes.append(note)
    return jsonify(note), 201

Ask the API

The test client lists the notes, adds one, and lists again. The prints show each answer.

client = app.test_client()
print(client.get("/api/notes").get_json())
print(client.post("/api/notes", json={"text": "Hi"}).status_code)
print(client.get("/api/notes").get_json())

Example

from flask import Flask, request, jsonify

app = Flask(__name__)

notes = []

@app.route("/api/notes")
def list_notes():
    return jsonify(notes)

@app.route("/api/notes", methods=["POST"])
def add_note():
    note = request.get_json()
    notes.append(note)
    return jsonify(note), 201

client = app.test_client()
print(client.get("/api/notes").get_json())
print(client.post("/api/notes", json={"text": "Hi"}).status_code)
print(client.get("/api/notes").get_json())

Key points

  • GET /api/notes returns the notes as JSON.
  • POST /api/notes adds a note from JSON.
  • A new note returns 201.
  • The notes live in a list while the app runs.

In this example, the notes live in a list. The GET route returns the list as JSON. The POST route adds the JSON body to the list. It returns the note with 201. The test client lists the empty notes, adds one, and lists again. The prints show the empty list, the 201 status, and the list with one note.

Note

An API speaks JSON, not HTML.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does POST /api/notes return after adding a note?