Skip to content
Tutorials Center
My learning

Topics

Lesson 60 of 72 ยท Projects

Project: A Todo REST API

Build a JSON todo API with Flask and SQLite. Add validation, consistent errors, pagination, signed bearer tokens, per-user data and automated tests.

A REST API has no pages and no forms. Its users are programs: a phone app, a JavaScript front end, a script. They send JSON and expect JSON back, with the right status code every time. In this project you build a todo API where each user registers, logs in to get a token, and manages their own list of todos.

You'll apply what you learned in Building JSON APIs, Designing a REST API, Validation and Serialization and API Authentication with Tokens, and finish with a test suite that proves it all works.

The project has two stages:

  1. A working CRUD API: SQLite storage, validation and a single JSON error format.
  2. Tokens, ownership and tests: register and login, bearer tokens, per-user data, filtering, pagination and 11 automated tests.

As before, there is no server in the browser. We call the API through the test client, which sends the same requests an HTTP client would.

The design

We decide the contract first, because an API is a promise to its callers.

Method and URL Auth Meaning Success
POST /api/v1/register no Create a user 201
POST /api/v1/login no Exchange credentials for a token 200
GET /api/v1/todos yes List your todos (?done=, ?page=, ?per_page=) 200
POST /api/v1/todos yes Create a todo 201 + Location
GET /api/v1/todos/<id> yes Read one 200
PATCH /api/v1/todos/<id> yes Change some fields 200
DELETE /api/v1/todos/<id> yes Delete 204

Every error uses one shape, so clients need only one error parser:

JSON
{"error": {"code": "validation_error", "message": "Invalid todo.", "details": {"title": "Title is required."}}}

The data model is small. Every todo belongs to exactly one user:

erDiagram
    USERS ||--o{ TODOS : owns
    USERS {
        int id PK
        text username
        text password_hash
    }
    TODOS {
        int id PK
        int user_id FK
        text title
        int done
    }

One user owns many todos. Every todo query will filter on user_id.

Stage 1: CRUD, validation and errors

This first version has no users yet. It shows the core ideas: one exception class for expected API errors, a function that validates and cleans input, and handlers that turn every error into the JSON shape above, including Flask's own 404 and 405.

The app keeps one SQLite connection in app.extensions. That is convenient for an in-memory demo database; a file-based database would open a connection per request, as in Using sqlite3 with Flask.

Python Stage 1: a todo API with validation

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 choices are worth noticing:

  • 422 Unprocessable Content for validation errors. The JSON was well-formed, but its contents were not acceptable. 400 is reserved for requests that cannot even be parsed.
  • PATCH for partial updates. Only the fields the client sent are validated and changed, so {"done": true} does not need a title.
  • 201 with a Location header tells the client where the new resource lives, and 204 means "deleted, nothing to send back".
  • Parameterized SQL (? placeholders) means a title like x'); DROP TABLE todos;-- is just text.
  • One error handler for HTTPException means even routes you never wrote (404, 405) answer in JSON instead of Flask's HTML pages.

Stage 2: tokens and ownership

An API open to the world is not a todo list; it is a public notepad. We add authentication in four steps.

  1. Register: store the username and a hash of the password with generate_password_hash (Password Hashing). Never store the password.
  2. Login: if check_password_hash succeeds, issue a token: here a signed value from itsdangerous.URLSafeTimedSerializer containing the user id. The server signs it with SECRET_KEY, so nobody can forge or change it.
  3. Call the API: clients send Authorization: Bearer <token> with every request.
  4. Check: a decorator verifies the signature and the age of the token, puts the user id on g, and every query then filters by that id.
sequenceDiagram
    participant C as Client
    participant A as API
    C->>A: POST /login (username, password)
    A-->>C: 200 {"token": "..."}
    C->>A: GET /todos (Authorization: Bearer token)
    A->>A: verify signature and age
    A-->>C: 200 your todos only
    C->>A: GET /todos (no or bad token)
    A-->>C: 401 + WWW-Authenticate: Bearer

The token proves who is calling without sending the password again.

Before building on tokens, look at how signing and expiry behave on their own:

Python Signed, expiring tokens with itsdangerous

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.

Tokens like this are signed, not encrypted: anyone holding one can decode its payload, so never put secrets in it. They also cannot be revoked before they expire without extra bookkeeping. Real systems often add refresh tokens or a token table; API Authentication with Tokens discusses the options, including JWT.

The complete app and its tests

Here is the finished API, with a built-in test suite at the bottom. It reuses the Stage 1 ideas and adds users, tokens, ownership, filtering and pagination. Pay attention to one habit: every todo query includes AND user_id = ?. A todo that belongs to someone else is answered with 404, exactly as if it did not exist, so the API does not even reveal which ids are taken.

Python Stage 2: tokens, ownership, pagination and 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.

Read the tests as a specification of the API. They cover the happy path (register, log in, create, read, update, delete), every error path the contract mentions, and the most important security property: one user can never see or change another user's todos. If you extend the API later, add a test first and the suite tells you when you break something.

The browser Python build has no PBKDF2 function, so the demo adds a small, slow pure-Python stand-in at the top (demo only; a real server needs nothing like it) and uses only 5,000 iterations so the examples run quickly. In a real app, keep Werkzeug's default settings, which are tuned to be slow on purpose. Also load SECRET_KEY from the environment and always serve a token API over HTTPS; a bearer token is a password for as long as it is valid.

Ideas to extend it

  • Add due dates, priorities or tags, and filter by them.
  • Move to Flask-SQLAlchemy models, or document the API with an OpenAPI file.
  • Return pagination links (next, prev) in the response.
  • Add rate limiting on /login to slow down password guessing.
  • Put it behind gunicorn and nginx as shown in Deployment.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A client sends valid JSON to create a todo, but the title is empty. Which status code best fits the response?

    The request was understood but its contents break the rules. 422 (or 400 for unparseable requests) tells the client to fix the input, not to retry.
  2. 2. User Bob requests /api/v1/todos/1, which belongs to Ada. Why does the API answer 404 instead of 403?

    Answering as if the todo does not exist avoids leaking which ids are in use. Every query is filtered by the caller's user id.
  3. 3. What does a signed token from URLSafeTimedSerializer guarantee?

    Signing proves integrity and origin, and the timestamp enables expiry. The payload itself is only encoded, not encrypted, and there is no built-in revocation.
  4. 4. Which header tells a client how to authenticate after a 401 response?

    WWW-Authenticate: Bearer names the authentication scheme the server expects.
  5. 5. Why is the registration endpoint storing generate_password_hash(password) instead of the password?

    Hashes are one-way and salted. Login compares the supplied password against the hash with check_password_hash.

Summary

  • Design the API contract first: resources, methods, status codes and one error format.
  • Validate every input on the server, answer with 422 and per-field details, and handle HTTPException so even 404 and 405 are JSON.
  • Use 201 with Location after creating, 204 after deleting, PATCH for partial updates.
  • Register with hashed passwords, log in for a signed expiring token, and protect routes with a Bearer decorator that answers 401 plus WWW-Authenticate.
  • Filter every query by the authenticated user so data stays private.
  • Tests through the test client document and protect the contract.

Next up: build another small service in Project: A URL Shortener.