Skip to content
Tutorials Center
My learning

Topics

Lesson 66 of 77 ยท Projects

Project: Todo JSON API

Build a Todo JSON API with plain Django: models, token authentication, input validation, per-user data, correct status codes and a test suite, all running live.

An API is a website for programs. Instead of HTML, it returns JSON, and instead of a person clicking links, a phone app or a JavaScript front end sends requests. In this project you will build a small Todo API with nothing but Django itself: no extra packages, so you can see exactly what each part does.

You will practice the pieces that every real API needs: token authentication (who is calling?), ownership (users see only their own todos), validation (reject bad input with a clear message), correct status codes, and tests. The earlier lessons Building JSON APIs and API Design introduce the ideas; here they come together.

The API we are building

Method and URL What it does Success status
GET /api/todos/ List your todos (?done=true, ?page=2) 200
POST /api/todos/ Create a todo 201
GET /api/todos/<id>/ Read one todo 200
PATCH /api/todos/<id>/ Change some fields 200
DELETE /api/todos/<id>/ Delete a todo 204

Every request must carry an Authorization: Token <key> header. The error statuses matter as much as the success ones, because a client program decides what to do from the number:

  • 400 the body is not valid JSON.
  • 401 no token, or an unknown token.
  • 404 the todo does not exist, or belongs to someone else.
  • 405 the method is not allowed on that URL.
  • 422 the JSON is fine but a field is invalid. (Some teams use 400 for this too; pick one and keep it consistent.)
flowchart LR
    A["Request"] --> B{"Valid token?"}
    B -->|"no"| C["401"]
    B -->|"yes"| D{"Valid JSON?"}
    D -->|"no"| E["400"]
    D -->|"yes"| F{"Fields valid?"}
    F -->|"no"| G["422 + field errors"]
    F -->|"yes"| H["Database"]
    H --> I["JSON response"]

A request must pass three checks, in this order, before it touches the database.

Design decision 1: keep validation pure

Validation is a decision about data: "is this payload acceptable, and what are the cleaned values or the errors?" That decision does not need a database, a request or Django at all. If you write it as a plain function that takes a dictionary and returns (clean, errors), it becomes trivial to test and to reuse. The same goes for reading the Authorization header.

The example below is plain Python. It runs a table of cases through both helpers, and these exact functions go into the full API afterwards.

Python Validation and token parsing as pure functions

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.

Notice that the validator checks isinstance(data["done"], bool). In JSON, "yes" is a string and 1 is a number; neither is the boolean true, and silently accepting them hides client bugs.

Design decision 2: tokens and ownership

Token authentication means the client sends a secret string that identifies a user. We store the token in its own table (ApiToken), linked to a user. A decorator, token_required, looks the token up, attaches the user to the request, and answers 401 with a WWW-Authenticate header when there is no valid token.

Because the token is sent in a header and not in a cookie, a malicious website cannot make a visitor's browser send it automatically, so the usual CSRF attack does not apply to these views. That is why they are marked @csrf_exempt. (If you ever switch the API to cookie sessions, you must turn CSRF checks back on.)

Ownership is enforced by one rule: every query starts from Todo.objects.filter(owner=request.user). A todo that belongs to someone else is simply not found, so the API answers 404 and does not even reveal that the id exists. Forgetting this filter is the most common serious bug in hand-written APIs, so it gets a dedicated test.

In a production system, store only a hash of each token (like a password) and show the key to the user once, so a database leak does not leak working credentials. Also give tokens an expiry and a way to revoke them. The demo stores the key directly to keep the code short.

The complete API, live, with tests

The next example is the whole project in one script: settings, models, helper functions, views, URLs, and a TestCase suite that runs at the end. Read it in the order it appears; in a real project the sections would be models.py, api_utils.py, views.py, urls.py and tests.py.

Two details to look for. read_json returns None for a body that is not a JSON object, which lets the view answer 400 before validation. And PATCH uses parse_todo(data, partial=True), so a client can send only the fields it wants to change.

Python The Todo API with 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.

Look at the tour output. A missing token gives 401; a new todo gives 201 with a Location header pointing to it; the empty title produces a 422 whose fields object names the bad field, so a client can show the message next to the right input. Page 2 contains the remaining todos, and deleting returns 204, a success with no body.

The test test_cannot_touch_other_users_todos is the one to remember. It asserts that Bob gets 404 for Ada's todo on read and delete, and that the row still exists afterwards.

What to improve before production

This API is deliberately small. A production version would add:

  • Hashed, expiring tokens and a login endpoint that issues them.
  • Rate limiting, so one client cannot hammer the server.
  • Versioned URLs (/api/v1/todos/) so you can change the format later without breaking old clients.
  • CORS headers if a browser app on another domain calls the API (see API Design).
  • A framework such as Django REST Framework once you have many endpoints: serializers, viewsets and pagination classes remove the repetition you can see in todo_list and todo_detail. The DRF overview shows how.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A user requests a todo that exists but belongs to another user. What should the API return?

    Filtering every query by the owner means other people's rows are never found. A 404 also avoids confirming that the id exists.
  2. 2. Why is @csrf_exempt acceptable on these token-authenticated views?

    CSRF attacks rely on the browser sending credentials automatically, as it does with cookies. A header-based token is only sent by code that knows it.
  3. 3. What is the benefit of writing parse_todo as a plain function instead of putting the checks inside the view?

    A function from dictionary to (clean values, errors) has no dependencies, so unit tests are tiny and the same rules serve POST and PATCH.
  4. 4. What does parse_todo(data, partial=True) allow for a PATCH request?

    With partial=True, a missing field is not an error. Fields that are present are still validated.
  5. 5. Which status code fits a successful DELETE with no response body?

    204 tells the client the action succeeded and there is nothing to read in the body.

Summary

  • A JSON API is a set of URLs, methods and status codes; clients rely on the status codes, so choose them deliberately (200, 201, 204, 400, 401, 404, 405, 422).
  • Keep validation in pure functions that return (clean, errors); it is easy to test and reuse for POST and PATCH.
  • Token authentication checks an Authorization: Token ... header and answers 401 with WWW-Authenticate when it fails; header-based tokens do not need CSRF protection.
  • Start every query from the current user's rows so users can never read or change each other's data.
  • read_json plus validation gives three distinct failures: 400 for bad JSON, 401 for no identity, 422 for bad fields.
  • Write tests for the failure paths, especially authentication and ownership.

Next lesson: Project: URL Shortener.