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.
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 path | Meaning | Success code | Body returned |
|---|---|---|---|
GET /todos | List todos (filter, paginate) | 200 OK | Page of todos |
POST /todos | Create a todo | 201 Created | The new todo, with its id |
GET /todos/42 | Read one | 200 OK | The todo |
PUT /todos/42 | Replace it entirely | 200 OK | The todo |
PATCH /todos/42 | Change some fields | 200 OK | The todo |
DELETE /todos/42 | Delete it | 204 No Content | Nothing |
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 each situation to the status code your API should return.
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).
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.
DELETE /todos/42 twice. The first call deletes it and returns 204. Which statement is true about the second call?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/42with{"title": "Buy oat milk"}gives{"title": "Buy oat milk", "done": false}.donefell back to its default.PATCH /todos/42with{"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.
| Method | Idempotent? | Why |
|---|---|---|
GET | Yes | Reads change nothing |
PUT | Yes | Replacing with the same data twice gives the same result |
DELETE | Yes | Gone is gone |
PATCH | Usually | {"done": true} is; {"views": "+1"} style increments are not |
POST | No | Two 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.
{"title": "Buy milk", "done": true}. A client sends PUT /todos/42 with {"done": false} and the API implements PUT correctly. What happens to title?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=40means "skip 40, give me 20". Easy, supports "jump to page 7", and maps to SQLLIMIT 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=1040means "give me 20 with id greater than 1040". The response includesnext_cursor. Fast at any depth (it uses the index onid) 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:
Page 1 is offset=0: the client sees todos 9, 8, 7.
Try both styles yourself:
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.
Using cursor_page from above with the same 7 todos, what does this print?
print(cursor_page(todos, 4, after=5))
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, notbool = 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:
limitwithle=100, search strings withmax_length.
def list_todos(done: bool = False). What is wrong with this filter?Practice
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), raiseConflictError(your route would turn this into409).get(todo_id)returns the todo orNone.list(done=None, limit=20, offset=0)returns todos in id order.done=Nonemeans no filter. Filter first, then applyoffsetandlimit.update(todo_id, **fields)is a PATCH: change only the given fields (titleand/ordone) and return the updated todo, orNoneif it does not exist. Any other field name raisesValueError. A title clash with a different todo raisesConflictError.delete(todo_id)returnsTrueif something was deleted, elseFalse.
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) # []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
idascending. Keep only items withid > after(afterisNonefor the first page). - Return at most
limititems. next_cursoris the id of the last returned item if more items remain after it, otherwiseNone.
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- 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.