Skip to content
Tutorials Center
My learning

Topics

Lesson 139 of 149 ยท Projects

Project: JSON API with Flask

Build a JSON REST API with Flask step by step. Add CRUD routes, input validation, JSON error handlers, filtering and pagination, then test it with the Flask test client.

Phone apps, single-page websites and other servers all talk to back ends through JSON APIs. In this project you'll build one with Flask: a small library service that stores books and lets clients list, create, read, update and delete them. It will reject bad input with helpful messages, answer every error in JSON, support filtering and pagination, and come with automated tests.

You met the ideas behind web frameworks in Web Development with Flask and Django: requests, routing, status codes and JSON. This project puts them into practice with the real framework. Along the way you'll use dictionaries, decorators, exceptions, type hints, classes and unit tests. The program grows in five stages, and each one is complete and runnable.

Running Flask in the browser

The editors on this page can't open a network port, so they can't run a real web server. They don't need to. Flask includes a test client, an object that sends requests straight to your application inside the same program and hands back the response. No network is involved, but your routes, validation and error handlers run exactly as they would on a server. It's the same tool you'll use for automated tests at the end of the project.

Flask isn't part of the standard library, so every example starts by installing it with micropip, the browser's version of pip (see Packages and pip). The first run downloads Flask from the Python Package Index and takes a few seconds, and it needs an internet connection. On your own computer you'd run pip install flask once in a virtual environment and leave those two lines out.

Stage 1: hello, Flask

A Flask application is an object created with Flask(__name__). You attach view functions to URLs with decorators such as @app.get(...), and whatever a view returns becomes the response. Return a dictionary and Flask converts it to JSON for you:

Python Stage 1: a first Flask app and the test client

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

<name> in the route is a URL variable: Flask matches any text in that position and passes it to the view as an argument. The test client's get() returns a response object with the status line, the headers and the body. The first two requests answer with application/json, because the views returned dictionaries.

Look at the third request, though. /books doesn't exist yet, and Flask answers with its default 404 page, written in HTML. A program calling a JSON API expects JSON even when things go wrong, so you'll fix that in stage 3.

Stage 2: reading and creating books

Now for the real resource. For this project, books live in a dictionary keyed by id, which is enough to learn the API side; the ideas at the end show how to swap in a database. The routes follow the REST conventions from the web development lesson:

Request Action Success status
GET /books list books 200 OK
POST /books create a book from the JSON body 201 Created
GET /books/<id> read one book 200 OK
Python Stage 2: list, read and create

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Several Flask features appear here:

  • <int:book_id> uses a converter. Flask only matches the route when that part of the URL is a whole number, and passes it as an int. /books/abc gets a 404 without ever reaching your code.
  • request.get_json() parses the JSON body of the current request. request looks like a global variable, but Flask gives every request its own value behind the scenes.
  • abort(404) stops the view immediately by raising an exception that Flask turns into a 404 response.
  • A view can return a tuple: (body, status, headers). Here the new book comes back with 201 Created and a Location header holding its URL, built by url_for() from the view's name, so it stays correct even if you change the route later.
  • client.open(url, method=..., json=...) sends any method and encodes the json argument as the request body. call() is a small helper that prints each exchange.

Flask normally sorts the keys of JSON objects alphabetically; app.json.sort_keys = False keeps them in the order the code builds them, which makes the output easier to read.

This version trusts its input completely. Post {"title": "Untitled"} without an author and add_book() raises a KeyError; Flask catches it and answers with 500 Internal Server Error, an HTML page that tells the client nothing useful. An API must never let bad input crash it, so validation comes next.

Stage 3: validation and JSON errors

Validation checks every field and collects all the problems, so a client can fix everything in one go instead of discovering mistakes one request at a time. Two kinds of bad input deserve different status codes:

  • 400 Bad Request: the body isn't JSON at all, so the server can't even read it.
  • 422 Unprocessable Content: the JSON is fine, but the values break the rules (a missing title, a year that's text).

Errors raised with abort() and Flask's own errors such as 404 and 405 are all subclasses of HTTPException from Werkzeug, the toolkit Flask is built on. One error handler for that base class turns every one of them into JSON:

Python Stage 3: validate input and answer errors in JSON

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Read the six responses from top to bottom:

  1. A valid book is created. The extra spaces around the title are gone, because the view stores the cleaned values, not the raw input.
  2. One request, four problems, all reported together under "fields": an empty title, a missing author, a year sent as text and an unknown field.
  3. A JSON array is valid JSON but not a book, so validate_book() reports the body itself.
  4. {title: oops} isn't valid JSON (keys need double quotes). get_json(silent=True) returns None instead of raising, and json_body() turns that into a 400 with a clear message.
  5. A missing book now gets a JSON 404 with a specific message.
  6. DELETE isn't allowed on that URL yet, so Flask answers 405 Method Not Allowed, also in JSON thanks to the same handler.

The status lines read 201 CREATED and 422 UNPROCESSABLE ENTITY because Werkzeug prints reason phrases in capitals, and it still uses the older name for 422; the current HTTP standard calls it Unprocessable Content. Clients only look at the number, so either name is fine.

Two details in validate_book() are easy to miss. type(year) is not int is stricter than isinstance() on purpose: in Python, True is an instance of int, so isinstance(True, int) is True, and a client could otherwise send "year": true. And the dictionary comprehension at the top reports unknown fields instead of silently ignoring them, which catches typos such as "auther" early.

Never show internal details in errors. The messages above describe what the client did wrong. Don't put tracebacks, SQL or file paths into API responses: they help attackers more than users. Log those on the server instead (see Logging and Warnings).

Stage 4: updating, deleting and querying

Two methods complete the CRUD set (create, read, update, delete):

  • PATCH /books/<id> changes only the fields in the body. Validation runs in partial mode: a missing title is fine, but an empty one isn't.
  • DELETE /books/<id> removes the book and answers 204 No Content, a success with an empty body.

The list endpoint also learns query parameters, so clients can ask for exactly what they need: ?author=quell filters, ?sort=year orders the results, and ?limit=2&offset=2 returns one page at a time. Paging matters as soon as a collection grows: nobody wants ten thousand books in one response.

Python Stage 4: the complete CRUD API

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A few design notes:

  • find_book() is shared by every route that takes an id, so "not found" behaves the same everywhere. Notice that deleting book 2 twice gives 204 and then 404.
  • request.args.get("limit", 10, type=int) reads a query parameter, converts it, and falls back to the default when the value is missing or isn't a number. The min()/max() around it clamp the result to 1โ€“100, so ?limit=1000000 can't make the server do a huge amount of work.
  • The sort key (b[sort] is None, b[sort]) is a tuple, compared item by item. Books without a year get True in the first position, which sorts after False, so they land at the end instead of crashing the comparison with None.
  • Unknown sort fields are rejected with a 400 rather than ignored, so a typo like ?sort=yaer doesn't silently return unsorted data.

PATCH changes only the fields it receives, which is why it suits most edits. Its sibling PUT replaces the whole resource: a PUT body must contain every field, and missing fields are reset. Many APIs offer both; this one keeps to PATCH.

Stage 5: an application factory and tests

The API works, but two things make it awkward to grow. The data lives in global variables, so every test would share (and pollute) the same books. And the app is created when the module is imported, so you can't make a fresh one with different settings.

The standard Flask answer is an application factory: a function, conventionally named create_app(), that builds and returns a new app each time it's called. Storage moves into a small BookStore class, and each app gets its own store. That makes testing clean: every test calls create_app() and starts from exactly the same data.

The tests use unittest and Flask's test client, the same one you've used all along:

Python Stage 5: application factory and automated tests

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

All six tests pass. Break something on purpose to see the tests do their job: change 201 to 200 in create_book(), or remove "pages" from the expected set, and run again.

Some things to notice:

  • Routes live inside create_app(), so each app gets its own store through the closure. For bigger projects, Flask's blueprints let you define routes in separate modules and register them inside the factory.
  • test_each_test_gets_fresh_data proves the isolation. It passes no matter which tests ran before it, even though another test deletes book 1 and another adds book 2, because setUp() builds a new app for every test.
  • app.testing = True makes unexpected exceptions in a view fail the test with the real traceback instead of turning into a vague 500 response.
  • find_book() uses or abort(...): if the store returns None, the right side runs and raises. It's a compact idiom, but use a plain if if you find it clearer.
  • BookStore hides how books are stored. Swap it for a class with the same methods that talks to SQLite, and the routes don't change.

Running it on your computer

To run the API as a real server, put stage 5 (without the micropip lines and the tests) in a file called library.py, then:

TEXT
python -m venv .venv
.venv\Scripts\activate          # Windows; on macOS/Linux: source .venv/bin/activate
pip install flask
flask --app "library:create_app()" run --debug

The --app option tells Flask to call your factory. The development server listens on http://127.0.0.1:5000, and you can call it from a second terminal with curl, which is built into Windows 10+, macOS and Linux:

TEXT
curl http://127.0.0.1:5000/books
curl -X POST http://127.0.0.1:5000/books -H "Content-Type: application/json" -d "{\"title\": \"Night Ferry\", \"author\": \"Juno Park\"}"
curl -X DELETE http://127.0.0.1:5000/books/1

Move the tests into test_library.py (importing create_app from library) and run them with python -m unittest. If you prefer pytest, the same assertions work as plain functions with a fixture that returns create_app().test_client().

Development server only. flask run --debug reloads on every change and shows an interactive debugger on errors, which is dangerous on a public machine. In production, run the app with a WSGI server such as Gunicorn (gunicorn "library:create_app()") behind a web server like nginx, and switch the in-memory store for a real database so data survives restarts.

Ideas to extend the API

  1. A database. Write a SqliteBookStore with the same methods as BookStore, using parameterized queries from Databases with sqlite3. Store tags in a separate table, or as a JSON string to start with.
  2. Search. Add ?q= to match words in the title, and test it.
  3. Full replacement with PUT. Add PUT /books/<id> that requires every field, and write tests that show how it differs from PATCH.
  4. Pagination links. Return "next" and "previous" URLs (built with url_for()) alongside the items, so clients don't have to compute offsets.
  5. API keys. Require an X-API-Key header for POST, PATCH and DELETE, answer 401 Unauthorized without it, and add tests for both cases.
  6. Typed validation. Rewrite validate_book() with a data class, or try the Pydantic library that FastAPI is built on.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does Flask's test client do?

    The test client calls the application without any network, so routes, validation and error handlers run exactly as they would behind a real server.
  2. 2. A client sends valid JSON, but the title is an empty string. Which status does this API return?

    The body could be read, so it's not a 400. The values break the rules, which this API reports as 422 with every invalid field listed.
  3. 3. Why does validate_book() use type(year) is not int instead of not isinstance(year, int)?

    bool is a subclass of int in Python. Checking the exact type rejects booleans that slipped into a numeric field.
  4. 4. What does the @app.errorhandler(HTTPException) function achieve?

    abort() and Flask's routing errors all raise HTTPException subclasses, so one handler gives every error the same JSON shape.
  5. 5. Why is an application factory such as create_app() useful for testing?

    With globals, one test's changes leak into the next. A fresh app per test (built in setUp) starts every test from the same known state.

Summary

  • A Flask app maps URLs and methods to view functions with decorators such as @app.get and @app.post; returning a dictionary sends JSON.
  • Converters like <int:book_id>, request.get_json(), request.args.get(..., type=int), abort() and (body, status, headers) tuples cover most API needs.
  • Validate every field, report all problems at once, and use 400 for unreadable bodies and 422 for invalid values.
  • One errorhandler for HTTPException makes every error, including 404 and 405, answer in JSON.
  • PATCH updates some fields, DELETE answers 204, and list endpoints should filter, sort and paginate with clamped limits.
  • An application factory plus a storage class keeps the app testable, and Flask's test client with unittest checks every behavior automatically.

Next: Stacks, Queues, Heaps and Linked Lists, where you'll build the classic data structures behind efficient programs.