Skip to content
Tutorials Center
My learning

Topics

Lesson 42 of 50 ยท Projects

Project: To-do API

Build a complete to-do REST API with FastAPI: Pydantic schemas, an in-memory store, CRUD endpoints, filters, pagination and a test suite you can run live.

Time to put the pieces together. In this project you will build a small but complete REST API for a to-do list: create, read, update and delete tasks, filter them, page through them, and prove it all works with tests. It uses only what the previous lessons taught: request bodies, Pydantic models, response models, partial updates, error handling and testing.

The data lives in memory, so it is gone when the app stops. That keeps the project focused on the API design; the URL shortener project adds a real database.

The plan

Decide the contract before writing code. A REST API is a set of nouns (resources) and verbs (HTTP methods):

Method and path Purpose Success Errors
POST /todos Create a task 201 + task 422 invalid body
GET /todos List with filters and paging 200 + list 422 bad query
GET /todos/{id} Read one task 200 + task 404
PATCH /todos/{id} Change some fields 200 + task 404, 422
DELETE /todos/{id} Remove a task 204, no body 404

Three schemas, one store

TodoCreate What the client sends to create.
TodoUpdate Every field optional, for PATCH.
Todo What the API returns, with an id.
Store A dict keyed by id.
1 / 2

Step 1: schemas and the store

Keep the input and output shapes separate. The client may not choose the id, so TodoCreate has none; the Todo returned by the API does. TodoUpdate makes every field optional so a PATCH can send just {"done": true}.

The store is a small class holding a dictionary and a counter. Putting it in a class, and building the app inside a function, means every call to create_app() gives a completely fresh API. That is what makes the tests in step 4 independent of each other.

Python
class TodoCreate(BaseModel):
    title: str = Field(min_length=1, max_length=100)
    done: bool = False
    priority: Literal["low", "normal", "high"] = "normal"
    due: date | None = None

class TodoUpdate(BaseModel):
    title: str | None = Field(default=None, min_length=1, max_length=100)
    done: bool | None = None
    priority: Literal["low", "normal", "high"] | None = None
    due: date | None = None

class Todo(TodoCreate):
    id: int

Literal limits priority to three words, so a typo such as "urgent" becomes a 422 instead of bad data in your list.

Step 2: the CRUD endpoints

Each endpoint is short because the schemas do the validation. Two details are worth noticing. A missing id raises HTTPException(404) through one helper, so the message is the same everywhere. And PATCH uses model_dump(exclude_unset=True), which contains only the fields the client actually sent, so omitting done does not reset it to False.

Python The to-do API: create, read, update, delete

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.

Check the output against the table in "The plan". Creating answers 201, a successful delete answers 204 with an empty body, and the invalid request reports both bad fields in one 422 response. You did not write any validation code for that.

Step 3: filters and paging

A list endpoint that returns everything is a time bomb. Add optional query parameters for the common questions: only finished tasks (done), tasks of one priority, a text search q, and paging with limit and offset. Each filter is applied only when the client supplied it. The total number of matches before paging goes into an X-Total-Count response header, so clients can show "page 2 of 7" (Query parameters covered Query() validation, and Performance and caching explains why page size needs a ceiling).

Python
@app.get("/todos", response_model=list[Todo])
async def list_todos(
    response: Response,
    done: bool | None = None,
    priority: Literal["low", "normal", "high"] | None = None,
    q: Annotated[str | None, Query(min_length=1, max_length=50)] = None,
    limit: Annotated[int, Query(ge=1, le=100)] = 20,
    offset: Annotated[int, Query(ge=0)] = 0,
):
    matches = [t for t in items.values()
               if (done is None or t.done == done)
               and (priority is None or t.priority == priority)
               and (q is None or q.lower() in t.title.lower())]
    response.headers["X-Total-Count"] = str(len(matches))
    return matches[offset:offset + limit]

Because done is bool | None, "not provided" (no filter) is different from false (only open tasks). That is the reason for the explicit is None checks.

Step 4: the test suite

Now the safety net. The file below contains the final app (with the new list endpoint) and a set of tests in the style of Testing FastAPI apps. The runner gives each test a fresh create_app(), so no test sees another's tasks. On your own machine these would be pytest functions; the logic is identical.

Python Final app with filters, paging and a test suite

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 test names from top to bottom: together they are a specification of the API. When you change behavior later, a failing test tells you exactly which promise you broke.

Ideas to extend it

  1. Add PUT /todos/{id} that replaces a whole task (see PUT, PATCH and partial updates).
  2. Sort the list with a sort parameter that accepts only created, due or priority.
  3. Return 400 when due lies in the past.
  4. Add a /todos/stats endpoint that counts open and finished tasks per priority. Remember that route order matters: declare it before /todos/{todo_id}.
  5. Protect the endpoints so each user sees only their own tasks, using OAuth2 and JWT.
  6. Swap the dictionary for SQLAlchemy (SQLAlchemy with FastAPI); thanks to find() only a few lines change.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does TodoCreate have no id field while Todo does?

    Separate input and output schemas keep server-controlled fields out of what the client may send.
  2. 2. What does model_dump(exclude_unset=True) give you in the PATCH endpoint?

    That is what lets a PATCH change done without resetting title or priority.
  3. 3. Which status code should a successful DELETE return in this API?

    204 means success with nothing to return. 404 is for ids that do not exist.
  4. 4. Why does create_app() build a new app and store on every call?

    A factory function means tests do not share data, so they can run in any order.

Summary

  • Design the contract first: resources, methods, status codes and error cases.
  • Use separate create, update and read schemas; Literal and Field constraints give you validation for free.
  • A store class (or dictionary) plus a find helper keeps CRUD endpoints short and the 404 message consistent.
  • exclude_unset=True makes PATCH update only what was sent.
  • Filter only when a parameter is provided, bound the page size and expose the total in a header.
  • Build the app in a factory so tests start from a clean state.

Next project: URL shortener, now with a database.