Build a REST API in Python from scratch
Authentication, validation, pagination, idempotency and clean errors, in a working API built with the standard library so you can see how each one works.
An authenticated, validated, paginated API with tests.
What proves the reviews API behaves as a service a separate client can depend on?
Define what each response means and exercise the whole request boundary. A successful response must match the contract and every rejected request should have the intended state effect.
Send an authenticated review creation
Validate the payload and store the review
List reviews with a cursor and confirm the new review appears
Send an authenticated review creation
Validate the payload and store the review
List reviews with a cursor and confirm the new review appears
Given Send an authenticated review creation and List reviews with a cursor and confirm the new review appears, write down the missing step that connects them.
Validate the payload and store the review
Now take Validate the payload and store the review and the result above. Write an input and an implementation that could produce this trace.
Send an authenticated review creation. Check that your implementation produces the result shown above.
How would you test that a rejected review did not slip into storage?
Submit an invalid review, check its documented error response, then query the list or test database and confirm the review count and contents are unchanged.
Check this when debugging. Validating input before checking whether the caller may use the endpoint at all.
Each lesson in this phase solved one problem. Real APIs have to solve all of them at once, on every request, without the parts getting in each other's way. Think of it as the point where you stop practicing single moves and play a full game. This capstone builds a product reviews API for the practice shop. It covers the main things you'd be expected to get right building a service at work, and it's the shape of the backend an AI feature usually sits behind.
404 Not Found, so nobody can probe which reviews exist
The review must stay. Answering 404 rather than 403 also avoids confirming that the review exists. This capstone puts rules like this together with paging, validation and one error shape.
"Customers should be able to post reviews of products through our API, read them page by page, and delete their own. Partner apps will call it with API keys, and our mobile app retries on bad connections."
Before you write code, turn that brief into a table, the way you'd sketch a floor plan before building. Each row is an endpoint, and the columns say what it needs and what it answers:
| endpoint | needs scope | success | errors |
|---|---|---|---|
POST /products/{sku}/reviews | reviews:write | 201 + the review | 401, 403, 404 (no such product), 422 (bad body) |
GET /products/{sku}/reviews?limit=&cursor= | reviews:read | 200 + a page | 401, 403, 404, 400 (bad cursor or limit) |
DELETE /reviews/{id} | reviews:write | 204 | 401, 403, 404 (no such review, or not yours) |
204, with no body
It worked, and there is nothing to send back.
Decisions, each from an earlier lesson:
Authorization: Bearer <key>. Each key has an owner and scopes. A missing or unknown key is 401; a missing scope is 403.rating is an integer from 1 to 5, text is 1 to 500 characters, and nothing else is allowed. Failures are 422 with details.Idempotency-Key header, so the mobile app's retries can't post the same review twice.{"error": {"type": ..., "message": ...}}.ALLOWED = {"rating", "text"}
def clean(body):
return {key: value for key, value in body.items() if key in ALLOWED}
print(
clean(
{"rating": 5, "text": "Great tent", "author_id": "usr_admin", "verified": True}
)
){'rating': 5, 'text': 'Great tent'}
The client tried to name itself the author and mark its own review as verified. The allowlist keeps the two fields a customer may set and drops the rest without comment. The author comes from the API key, on the server, never from the body.
So nobody can learn which review ids exist by probing for 403s
A 403 would confirm the id exists. Answering 404 for "not yours" gives an outsider nothing to learn.
Write get_owned(reviews, review_id, user): return the review with that id if user wrote it (its author equals user). Raise NotFound both when the review doesn't exist and when someone else wrote it, so a stranger can't tell the two apart.
class NotFound(Exception): pass REVIEWS = {"rv_1": {"id": "rv_1", "author": "ada", "text": "Great tent."}} def get_owned(reviews, review_id, user): return reviews[review_id] print(get_owned(REVIEWS, "rv_1", "ada"))
Write a sentence or two, then compare it with a good answer in the lesson.
An airport runs its checks in a fixed order: passport first, then boarding pass, then your bag, and only then the gate. Nobody inspects your luggage before they know you're allowed to travel. An API needs the same discipline, both for security and for clear errors:
Checking the scope before validating means an unauthorized caller learns nothing about your schemas. Validating before touching the database means bad input never reaches SQL.
In plain words: ask "who are you?" and "may you do this?" before you look at anything they sent.
The earlier the check, the less a failing caller learns.
Run the checks in the wrong order and your errors leak information. Here are two handlers given the same request from someone with no key.
KEYS = {"key-123"}
PRODUCTS = {7: "Tent"}
def wrong_order(key, product_id):
if product_id not in PRODUCTS:
return 404
if key not in KEYS:
return 401
return 200
def right_order(key, product_id):
if key not in KEYS:
return 401
if product_id not in PRODUCTS:
return 404
return 200
for pid in [7, 8]:
print(
"product",
pid,
"wrong order:",
wrong_order(None, pid),
" right order:",
right_order(None, pid),
)With the wrong order, a stranger can tell that product 7 exists and product 8 doesn't, without any key. The right order gives both the same 401. The same slip can reveal which customer ids or email addresses are real.
def check(has_key, valid_body): if not has_key: return 401 if not valid_body: return 422 return 200 print(check(False, False))
401
has_key is False, so the first test returns 401 before the body is ever looked at. Authentication comes first, so someone without a key learns nothing about your validation.
The whole service is a class with one method, handle(method, path, headers, body), returning (status, headers, body). Picture one front counter that every request walks up to. Production wraps it in a real server, as you saw with WSGI. Tests walk up to the same counter directly, with an in-memory database, so every requirement in the table above becomes a one-line check.
reviews:write scope sends a badly formed body to create a review. What should it get?403, because the scope is checked before the body is validated
Authorizing before validating means an unauthorized caller learns nothing about your schemas.
A miniature version of the pattern: a service with one endpoint, and the tests a reviewer would expect.
class Pinger: def __init__(self, keys): self.keys = keys def handle(self, method, path, headers, body=None): if (method, path) != ("GET", "/ping"): error = {"type": "not_found_error", "message": "no such route"} return 404, {}, {"error": error} key = headers.get("authorization", "").removeprefix("Bearer ") if key not in self.keys: error = {"type": "authentication_error", "message": "bad key"} return 401, {}, {"error": error} return 200, {}, {"pong": self.keys[key]} api = Pinger({"k_ada": "ada"}) tests = [ (("GET", "/ping", {"authorization": "Bearer k_ada"}), 200), (("GET", "/ping", {}), 401), (("GET", "/pong", {"authorization": "Bearer k_ada"}), 404), ] for args, want in tests: got = api.handle(*args)[0] print("PASS" if got == want else "FAIL", args[:2], got)
Each row is a request and the status it should get. Once the API is one function, the test list reads like the design table. Writing that table first, then the code, is TDD at the scale of a whole service.
The same Pinger can be called over HTTP too. serve wraps a WSGI app so requests reaches it, as a client of your finished service would. The WSGI function below only translates between the two worlds: it turns environ into the arguments of handle, and the returned tuple into a status line and a body.
import json import requests from devserver import serve class Pinger: def __init__(self, keys): self.keys = keys def handle(self, method, path, headers, body=None): if (method, path) != ("GET", "/ping"): return 404, {}, {"error": {"type": "not_found_error"}} key = headers.get("authorization", "").removeprefix("Bearer ") if key not in self.keys: return 401, {}, {"error": {"type": "authentication_error"}} return 200, {}, {"pong": self.keys[key]} api = Pinger({"k_ada": "ada"}) PHRASES = {200: "OK", 401: "Unauthorized", 404: "Not Found"} def wsgi(environ, start_response): headers = {"authorization": environ.get("HTTP_AUTHORIZATION", "")} method, path = environ["REQUEST_METHOD"], environ["PATH_INFO"] status, _, body = api.handle(method, path, headers) ctype = [("Content-Type", "application/json")] start_response(f"{status} {PHRASES[status]}", ctype) return [json.dumps(body).encode()] base = serve(wsgi) calls = [("/ping", "Bearer k_ada"), ("/ping", ""), ("/pong", "Bearer k_ada")] for path, auth in calls: r = requests.get(base + path, headers={"Authorization": auth}) print(r.status_code, r.json())
The same three requests as the test list, now over HTTP, give the same three statuses.
The order of checks decides which error a client sees. Write first_failure(request, checks): call each check with the request, in order; each returns None (passed) or a (status, message) tuple. Return the first failure, or (200, "ok") if every check passes. Later checks shouldn't run once one fails.
def first_failure(request, checks): failures = [c(request) for c in checks] return failures[-1] or (200, "ok") def authenticated(r): return None if r.get("key") else (401, "missing key") def has_scope(r): return None if "reviews:write" in r.get("scopes", []) else (403, "missing scope") def valid_body(r): return ( None if r.get("body", {}).get("stars") in range(1, 6) else (422, "stars must be 1 to 5") ) print( first_failure( {"key": "k1", "scopes": [], "body": {"stars": 9}}, [authenticated, has_scope, valid_body], ) )
Write a sentence or two, then compare it with a good answer in the lesson.
Pilots read a checklist before every flight, however many hours they've flown. Here's a review checklist for any API you build:
The exercise at the end of this lesson builds the core of the reviews API, with helpers from earlier lessons given in compact form. Before it ships, review it as a teammate would, and then see what a reviewer misses.
Lists are paginated with a limit cap, so nothing returns unbounded data
Unbounded lists are a common way to take an API down. The other three are mistakes the lesson warns against.
Don't validate before you authorize. A door guard shouldn't explain what's wrong with your fake ID. If an unauthorized caller gets a detailed list of what's wrong with their request, you've taught a stranger how your API works. Check the scope first, then validate.
403 can confirm that something exists. A clerk who says "I can't show you that file" has told you there's a file. If a user asks for someone else's order and gets 403, they've learned that the order exists. Answer 404, exactly as if it didn't, and no one can use your API to probe for valid ids.
That the order exists
"I can't show you that" confirms there is something to show. Answering 404, as if it didn't exist, gives nothing away.
Keep idempotency keys per client. Two restaurants can hand out the same ticket number, and neither should give you the other's meal. If two clients happen to use the same key and you share a single list, the second client receives the first client's response, which might include someone else's data. Store each key along with the client it belongs to.
Don't count rows to find out if there are more. To learn whether a book has another page, you turn one page. You don't count the rest. SELECT COUNT(*) on a large table is slow, and you only need a yes or no. Ask for one row more than the page size. If it comes back, there's another page, and you drop it from the response. It's a small trick that works at any size.
The partner team likes the reviews API and wants it on the stack the rest of the company uses. You built the checks by hand, so you know exactly what a framework must do for you.
Rebuild the three endpoints in FastAPI. The hard part is keeping the order of checks, and the 404-for-not-yours rule, once the framework starts doing some of them before your code runs.
from fastapi import FastAPI app = FastAPI(title="Reviews API") REVIEWS = {} KEYS = { "key-write": {"owner": "ada", "scopes": ["reviews:read", "reviews:write"]}, "key-read": {"owner": "lin", "scopes": ["reviews:read"]}, } # your code: models, a dependency for the key, and the three routes print(app.title, sorted(KEYS))
A reviews API is the shape of the backend an AI feature sits behind: a model that summarizes reviews, scores their tone, or answers questions about them calls these same routes. The checks, the error shape and the tests carry over unchanged. In Documenting APIs with OpenAPI you turn routes like these into tools a model can call, and in Capstone: a streaming chat service the phase ends with a service that streams a model's reply behind the same kind of checks. Goes deeper in: Project: a FastAPI service with accounts rebuilds a service like this on a database with accounts, and [[p11-testing-in-production]] covers what to watch once it ships.
Write a sentence or two, then compare it with a good answer in the lesson.
Start with a short baseline or choose guided, independent, or AI-assisted practice.
In what order should an endpoint check things?
575 lessons in thirteen phases. 176 are free without an account, and a free account opens the rest. See every lesson.
Authentication, validation, pagination, idempotency and clean errors, in a working API built with the standard library so you can see how each one works.
Go from your first line of code to working as a Python developer: projects, testing, data, databases, web apps and APIs, all in your browser.
Design, test, deploy, and operate an HTTP API that another engineer can use.
Never trained an AI? Teach a small one to write, right in your browser. It takes about 20 seconds and needs no account. Teach it to write