Skip to content

Lesson 10 of 59Building a real API

Designing a CRUD API

Design REST endpoints for a resource with the right methods, status codes, PUT vs PATCH, pagination and filtering.

16 min read0/5 questions

You can now read typed, validated input from the URL and the body. This unit puts those pieces together into a complete API, starting with its shape. Most backend work is CRUD: Create, Read, Update, Delete records. It sounds simple, yet API reviews and interviews keep catching the same mistakes: 200 for everything, PUT that wipes fields, pagination that skips rows. Getting the conventions right means any frontend developer can guess how your API works before reading the docs.

Resources and URLs

REST APIs are organised around resources: the nouns of your app (todos, users, orders). Each resource gets two kinds of URL. The collection is plural (/todos), and an item adds its id (/todos/42). The HTTP method says what to do, so the URL never contains verbs like /getTodo or /deleteTodo.

Method and pathMeaningSuccess codeBody returned
GET /todosList todos (filter, paginate)200 OKPage of todos
POST /todosCreate a todo201 CreatedThe new todo, with its id
GET /todos/42Read one200 OKThe todo
PUT /todos/42Replace it entirely200 OKThe todo
PATCH /todos/42Change some fields200 OKThe todo
DELETE /todos/42Delete it204 No ContentNothing

Related resources can nest one level, like GET /users/7/todos, when the child only makes sense inside the parent. Deeper nesting (/users/7/projects/3/todos/42/comments) gets painful fast; give the deep thing its own top-level path instead.

Status codes that carry meaning

The status code is the first thing a client checks, so it has to be honest. The errors you will use most:

  • 400 Bad Request: the request makes no sense in a way validation does not cover.
  • 401 Unauthorized: you are not logged in (missing or bad credentials).
  • 403 Forbidden: you are logged in but not allowed to do this.
  • 404 Not Found: no such resource (or you may not know it exists).
  • 409 Conflict: the request clashes with current state, like signing up with an email that is already taken.
  • 422 Unprocessable Content: input failed validation. FastAPI sends this for you.
Match the pairs0/5 matched

Match each situation to the status code your API should return.

Choose an item, then its match on the other side.

The todo API in FastAPI

Here is a complete CRUD router. It uses the schemas from the Pydantic lesson and a repository object that stores todos (you will build it in the challenge, and swap it for a real database in Databases with SQLAlchemy, early in the next unit).

app/main.py
from typing import Annotated
 
from fastapi import FastAPI, HTTPException, Query, Response, status
 
from app.repository import ConflictError, TodoRepository
from app.schemas import TodoCreate, TodoRead, TodoUpdate
 
app = FastAPI()
repo = TodoRepository()
 
 
@app.get("/todos")
def list_todos(
    done: bool | None = None,
    limit: Annotated[int, Query(ge=1, le=100)] = 20,
    offset: Annotated[int, Query(ge=0)] = 0,
) -> list[TodoRead]:
    return repo.list(done=done, limit=limit, offset=offset)
 
 
@app.post("/todos", status_code=status.HTTP_201_CREATED)
def create_todo(body: TodoCreate, response: Response) -> TodoRead:
    try:
        todo = repo.create(body.title)
    except ConflictError:
        raise HTTPException(status.HTTP_409_CONFLICT, "A todo with that title exists")
    response.headers["Location"] = f"/todos/{todo['id']}"
    return todo
 
 
@app.get("/todos/{todo_id}")
def get_todo(todo_id: int) -> TodoRead:
    todo = repo.get(todo_id)
    if todo is None:
        raise HTTPException(status.HTTP_404_NOT_FOUND, "Todo not found")
    return todo
 
 
@app.patch("/todos/{todo_id}")
def update_todo(todo_id: int, body: TodoUpdate) -> TodoRead:
    todo = repo.update(todo_id, **body.model_dump(exclude_unset=True))
    if todo is None:
        raise HTTPException(status.HTTP_404_NOT_FOUND, "Todo not found")
    return todo
 
 
@app.delete("/todos/{todo_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_todo(todo_id: int) -> None:
    if not repo.delete(todo_id):
        raise HTTPException(status.HTTP_404_NOT_FOUND, "Todo not found")

Notice that the routes are thin. Each one translates HTTP into a repository call and translates the result back (a None becomes a 404, a ConflictError becomes a 409). The Location header on a 201 tells the client the URL of what it just created.

Quick check
A client calls DELETE /todos/42 twice. The first call deletes it and returns 204. Which statement is true about the second call?
Need a nudge? A hint rules out a wrong answer.

PUT vs PATCH, and idempotency

PUT replaces the whole resource with what you send. Fields you leave out are reset to their defaults or removed. PATCH updates only the fields you send. For a todo {"title": "Buy milk", "done": true}:

  • PUT /todos/42 with {"title": "Buy oat milk"} gives {"title": "Buy oat milk", "done": false}. done fell back to its default.
  • PATCH /todos/42 with {"title": "Buy oat milk"} gives {"title": "Buy oat milk", "done": true}.

Most modern APIs use PATCH for edits, implemented with model_dump(exclude_unset=True) so absent fields are left alone.

An operation is idempotent if doing it twice has the same effect as doing it once. That matters because networks fail: a client that never got a response will retry.

MethodIdempotent?Why
GETYesReads change nothing
PUTYesReplacing with the same data twice gives the same result
DELETEYesGone is gone
PATCHUsually{"done": true} is; {"views": "+1"} style increments are not
POSTNoTwo POSTs create two todos

For POSTs that must not happen twice (payments, orders), clients send an idempotency key header. The server stores the key with the result and returns the stored result if the same key arrives again.

Quick check
Stored todo: {"title": "Buy milk", "done": true}. A client sends PUT /todos/42 with {"done": false} and the API implements PUT correctly. What happens to title?
Need a nudge? A hint rules out a wrong answer.

Pagination

Never return an unbounded list. A GET /todos that returns 2 million rows will time out, use gigabytes of memory, and hand the client data it cannot display. Two common styles:

  • Limit/offset: ?limit=20&offset=40 means "skip 40, give me 20". Easy, supports "jump to page 7", and maps to SQL LIMIT 20 OFFSET 40. Two problems: the database still walks past all skipped rows (slow at offset 1,000,000), and rows shift when data changes.
  • Cursor (keyset): ?limit=20&after=1040 means "give me 20 with id greater than 1040". The response includes next_cursor. Fast at any depth (it uses the index on id) and stable while data changes, but no jumping to an arbitrary page.

Watch what goes wrong with offsets when a new todo is inserted while someone is paging, newest first:

Offset pagination while data changes (newest first, limit 3)
9
0
8
1
7
2
6
3
5
4
4
5

Page 1 is offset=0: the client sees todos 9, 8, 7.

1/4

Try both styles yourself:

Pythonpagination.py
todos = [{"id": i, "title": f"Todo {i}"} for i in range(1, 8)] def offset_page(items, limit, offset): return [t["id"] for t in items[offset : offset + limit]] def cursor_page(items, limit, after=None): rest = [t for t in items if after is None or t["id"] > after] page = rest[:limit] next_cursor = page[-1]["id"] if len(rest) > limit else None return [t["id"] for t in page], next_cursor print(offset_page(todos, 3, 0), offset_page(todos, 3, 3)) ids, cursor = cursor_page(todos, 3)print(ids, cursor)ids, cursor = cursor_page(todos, 3, after=cursor)print(ids, cursor)ids, cursor = cursor_page(todos, 3, after=cursor)print(ids, cursor)
Output
Press Run (⌘ Enter) to see what happens.

The last page returns None as the cursor: that is how the client knows to stop. A paginated response usually wraps the items in an envelope, such as {"items": [...], "next_cursor": 6}, rather than returning a bare list, so you can add fields later without breaking clients.

Predict the outputPython

Using cursor_page from above with the same 7 todos, what does this print?

print(cursor_page(todos, 4, after=5))
Need a nudge? Hints walk you through it.

Filtering and sorting

Filters and sorting are query parameters on the collection: GET /todos?done=false&q=milk&sort=-created_at. A few conventions keep them predictable:

  • A filter that is absent means "do not filter". Use bool | None = None, not bool = False, or you can never list done and not-done together.
  • For sorting, a leading - commonly means descending. Restrict the allowed fields with an enum so nobody sorts by an unindexed column.
  • Validate and cap everything: limit with le=100, search strings with max_length.
Quick check
def list_todos(done: bool = False). What is wrong with this filter?
Need a nudge? A hint rules out a wrong answer.

Practice

ChallengeMedium

In-memory todo repository

Build the storage layer behind a CRUD API. Write TodoRepository (a ConflictError exception class is given):

  • create(title) stores {"id", "title", "done": False} and returns it. Ids start at 1 and go up by one. Ids are never reused, even after a delete. If another todo already has the same title (case-insensitive), raise ConflictError (your route would turn this into 409).
  • get(todo_id) returns the todo or None.
  • list(done=None, limit=20, offset=0) returns todos in id order. done=None means no filter. Filter first, then apply offset and limit.
  • update(todo_id, **fields) is a PATCH: change only the given fields (title and/or done) and return the updated todo, or None if it does not exist. Any other field name raises ValueError. A title clash with a different todo raises ConflictError.
  • delete(todo_id) returns True if something was deleted, else False.

Return copies of stored dicts, so a caller mutating a result cannot change what is stored.

repo = TodoRepository()
repo.create("Buy milk")        # {"id": 1, "title": "Buy milk", "done": False}
repo.update(1, done=True)      # {"id": 1, "title": "Buy milk", "done": True}
repo.list(done=False)          # []
Python
class ConflictError(Exception): pass class TodoRepository: def __init__(self): pass def create(self, title: str) -> dict: pass def get(self, todo_id: int) -> dict | None: pass def list( self, done: bool | None = None, limit: int = 20, offset: int = 0 ) -> list[dict]: pass def update(self, todo_id: int, **fields) -> dict | None: pass def delete(self, todo_id: int) -> bool: pass
ChallengeEasy

Cursor pagination

Write cursor_page(items, limit, after) for keyset pagination.

items is a list of dicts with an integer "id" (not necessarily sorted). Return:

{"items": [...], "next_cursor": <id or None>}
  • Sort by id ascending. Keep only items with id > after (after is None for the first page).
  • Return at most limit items.
  • next_cursor is the id of the last returned item if more items remain after it, otherwise None.
items = ids 1..5, limit 2, after None  ->  ids [1, 2], next_cursor 2
items = ids 1..5, limit 2, after 4     ->  ids [5],    next_cursor None
Python
def cursor_page(items: list[dict], limit: int, after: int | None) -> dict: pass
Key terms
resource
A noun your API exposes, with a collection URL (/todos) and item URLs (/todos/42).
idempotent
Doing it twice has the same effect as once. GET, PUT and DELETE are; POST is not.
PATCH vs PUT
PATCH changes only the fields sent. PUT replaces the whole resource.
409 Conflict
The request clashes with current state, like a duplicate unique value.
cursor pagination
Ask for items after the last one seen (?after=1040). Fast at any depth and stable when data changes.