Skip to content
Index Ai Academy
Phase 8 · Design at scale

Project: a reviews API

An authenticated, validated, paginated API with tests.

About 45 minutes · A free account opens the whole lesson.
Already have an account? Sign in to open this lesson

What it covers9

First principles

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.

  1. Starting point

    Send an authenticated review creation

  2. What changes

    Validate the payload and store the review

  3. Result

    List reviews with a cursor and confirm the new review appears

Compare all three steps
  1. Starting point

    Send an authenticated review creation

  2. What changes

    Validate the payload and store the review

  3. Result

    List reviews with a cursor and confirm the new review appears

Complete and reverse the trace

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.

Compare with the worked step

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.

Check one starting point

Send an authenticated review creation. Check that your implementation produces the result shown above.

Try it on a new case

How would you test that a rejected review did not slip into storage?

Show worked reasoning

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.

Run, change, and build

Check this when debugging. Validating input before checking whether the caller may use the endpoint at all.

Trace the cause · HTTP request, job, and result
  1. Identify the request, response, and any durable state. Predict the status or stored result before following the trace.
  2. Change one request property and keep the client contract visible. Compare the response and job state to explain the observed behavior.
  3. Try the same reasoning on this case. How would you test that a rejected review did not slip into storage?

Why it matters

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.

What you'll be able to do

  • Design a small API end to end: resources, routes, schemas, errors and auth
  • Combine authentication, scopes and object-level checks on every endpoint
  • Wire validation, persistence, cursor pagination and idempotency into one service
  • Test the whole API through a single entry point, then call it over HTTP and review it for security faults
Quick check
A customer's API key tries to delete a review someone else wrote. What should the API return?
  1. 404 Not Found, so nobody can probe which reviews exist
  2. 200 OK, and go ahead and delete the review anyway
  3. 201 Created, since a change to the data was made
  4. 500 Internal Server Error, since something failed
Show the answer

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.

The brief: reviews for the practice shop

"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."

The design

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:

endpointneeds scopesuccesserrors
POST /products/{sku}/reviewsreviews:write201 + the review401, 403, 404 (no such product), 422 (bad body)
GET /products/{sku}/reviews?limit=&cursor=reviews:read200 + a page401, 403, 404, 400 (bad cursor or limit)
DELETE /reviews/{id}reviews:write204401, 403, 404 (no such review, or not yours)
Quick check
In the table, what does a successful DELETE answer?
  1. 200, with the deleted review
  2. 202, with a job id
  3. 204, with no body
  4. 201, with a Location header
Show the answer

204, with no body

It worked, and there is nothing to send back.

Decisions, each from an earlier lesson:

  • Auth: Authorization: Bearer <key>. Each key has an owner and scopes. A missing or unknown key is 401; a missing scope is 403.
  • Object-level check: you may only delete reviews you wrote. Someone else's review answers 404, so ids can't be probed.
  • Validation: a JSON Schema for the body. rating is an integer from 1 to 5, text is 1 to 500 characters, and nothing else is allowed. Failures are 422 with details.
  • Pagination: cursor-based, ordered by review id, newest last.
  • Idempotency: POST accepts an Idempotency-Key header, so the mobile app's retries can't post the same review twice.
  • Errors: always {"error": {"type": ..., "message": ...}}.
Quick check
From the lesson on a database-backed API: a server that copies every key from a request lets a client set fields it shouldn't. An allowlist stops that. What does this print?
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}
    )
)
  1. {}
  2. {'author_id': 'usr_admin', 'verified': True}
  3. {'rating': 5, 'text': 'Great tent', 'verified': True}
  4. {'rating': 5, 'text': 'Great tent'}
Show the answer

{'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.

Quick check
Lin's key tries to delete a review Ada wrote. Why answer 404 rather than 403?
  1. So nobody can learn which review ids exist by probing for 403s
  2. Because 404 is faster to compute than 403 is
  3. Because the review really doesn't exist for Lin's company
  4. Because 403 is only for admins, and Lin isn't an admin
Show the answer

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.

Drill

Owned, or not found

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"))
In the lesson, your code is checked as you write it.
In your own words
Why answer 404 rather than 403 for someone else's review?

Write a sentence or two, then compare it with a good answer in the lesson.

Build it: the order of checks, and one entry point

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:

  1. Route: does the method and path exist? (404 or 405)
  2. Authenticate: is there a valid key? (401). Do this before anything that touches data.
  3. Authorize the action: does the key have the scope? (403)
  4. Validate input: the body, the query parameters, the cursor. (422 or 400)
  5. Load and check objects: does the product exist? Is this review the caller's? (404)
  6. Do the work in one transaction, and build the response.

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.

Try it now

The earlier the check, the less a failing caller learns.

Worked example

What a stranger can learn

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),
    )
It runs right here in your browser, with nothing to install.

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.

Quick check
What does this print?
def check(has_key, valid_body):
    if not has_key: return 401
    if not valid_body: return 422
    return 200
print(check(False, False))
  1. 401
  2. 200
  3. 400
  4. 422
Show the answer

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.

One entry point, many tests

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.

Quick check
A key without the reviews:write scope sends a badly formed body to create a review. What should it get?
  1. 401, because the key isn't valid for creating reviews
  2. 422, listing what's wrong with the body, field by field
  3. 201, since the review is created and fixed up later
  4. 403, because the scope is checked before the body is validated
Show the answer

403, because the scope is checked before the body is validated

Authorizing before validating means an unauthorized caller learns nothing about your schemas.

Worked example

Testing an API through one function

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)
In the lesson you can change this and run it.

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.

Drill

Run the checks in order

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],
    )
)
In the lesson, your code is checked as you write it.
In your own words
In what order are checks run on each request, and what does an early check protect?

Write a sentence or two, then compare it with a good answer in the lesson.

Ship it: review it, then break it

Pilots read a checklist before every flight, however many hours they've flown. Here's a review checklist for any API you build:

  • Every endpoint authenticates, checks scopes, and checks object ownership.
  • Every input is validated, and every error uses the one error shape.
  • Lists are paginated with a limit cap; nothing returns unbounded data.
  • Writes that clients may retry accept idempotency keys.
  • SQL uses placeholders, and any column names come from allowlists.
  • Responses carry request ids; logs are structured and free of secrets.
  • There's an OpenAPI spec, and CI runs the tests and a breaking-change check.

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.

Quick check
Which of these is on the lesson's review checklist for any API?
  1. Lists are paginated with a limit cap, so nothing returns unbounded data
  2. Each handler picks its own error shape, to suit what went wrong
  3. Every endpoint returns 200, so clients never break on an error
  4. Column names in SQL come straight from the request, for flexibility
Show the answer

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.

Mistakes this project is designed to catch

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.

Quick check
A user asks for someone else's order and gets 403. What have they learned?
  1. That their key has expired
  2. Nothing at all
  3. That the order exists
  4. Who the order belongs to
Show the answer

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.

Portfolio brief

Rebuild the reviews API in FastAPI

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.

It must

  • POST /products/{sku}/reviews, GET /products/{sku}/reviews and DELETE /reviews/{id} exist, with the same statuses as the design table
  • A missing or unknown key is 401 and a key without the scope is 403, both before the body is validated
  • The body is a pydantic model with a rating from 1 to 5 and a text of 1 to 500 characters
  • Someone else's review answers 404 on delete, the same as a review that does not exist
  • Every error has one shape, with a type and a message
  • A test calls the app with httpx.ASGITransport and checks one request for each status in the table

Go further

  • Cursor paging with a limit cap of 50
  • An Idempotency-Key header on POST, kept per owner
  • A per-key token bucket that answers 429 with Retry-After
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))
In the lesson, you build it here and the tutor can review it.

Where this fits, and what comes next

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.

In your own words
Why is answering 404, not 403, for someone else's review part of shipping safely?

Write a sentence or two, then compare it with a good answer in the lesson.

Choose how to practice

Start with a short baseline or choose guided, independent, or AI-assisted practice.

Practice what you just read

  • 3 code examples you can edit and run
  • a practice exercise that checks your code
  • a 5-question quiz
  • 8 review cards for spaced repetition

Try a quiz question

In what order should an endpoint check things?

  1. Route, authenticate, authorize (scope), validate input, load and check objects, then do the work
  2. Validate input, do the work, and then check the key, so that clients with bad input get told quickly
  3. Do the work first and authenticate afterward, undoing the work if the key turns out to be invalid
  4. The order doesn't matter, as long as every check runs before the response is sent back to the client

Answer it at the end of the lesson to see if you're right, and why.

Before this lesson

Keep learning

Where this lesson leads.

575 lessons in thirteen phases. 176 are free without an account, and a free account opens the rest. See every lesson.

Phase 8 · about 23 hours of study

APIs

Design, build, secure and scale web APIs from first principles 27 lessons 1 free
  1. HTTP from the wire up FreeWhat really travels between client and server: bytes, headers and bodies.40 min
  2. API stylesREST, RPC, GraphQL, gRPC and streaming: what each is for.35 min
  3. Build an API server from scratchRouting, handlers and responses, with no framework.45 min
  4. A web framework, from the insideDecorators, middleware and error handling: how Flask and FastAPI work.40 min
  5. Designing a REST APIResources, methods, status codes, errors and pagination done well.45 min
  6. Validating requests with schemasCheck every request against a JSON Schema and say exactly what's wrong.45 min
  7. A database-backed APICRUD endpoints on SQLite, with safe concurrent updates.45 min
  8. Authentication and authorizationAPI keys, sessions, tokens and OAuth: who's calling, and what may they do?45 min
  9. Rate limits, retries and idempotencyKeep an API up under load and make retries safe.45 min
  10. Async HTTP clientsMany requests at once with asyncio and httpx: limits, timeouts and retries.45 min
  11. Webhooks and eventsPush events to other systems: signed, retried and deduplicated.45 min
  12. Documenting APIs with OpenAPIA machine-readable contract for docs, SDKs and AI tools.40 min
  13. Running APIs in productionVersioning, CORS, caching, request ids and health checks.45 min
  14. Project: a reviews APIAn authenticated, validated, paginated API with tests.45 min
  15. Web pages with FlaskRoutes, Jinja templates, a shared layout, links and error pages, tested with the test client.45 min
  16. Forms and redirectsGET and POST, validation messages, post/redirect/get, flash messages and CSRF tokens.45 min
  17. Accounts and loginsPassword hashing with bcrypt, sessions, pages that need a login, and safe logout.45 min
  18. Project: a trail log web appA multi-page app with a database, accounts, forms and tests.45 min
  19. JavaScript for Python programmersVariables, functions, arrays and objects mapped from Python, and the traps: truthy empty arrays, for...in and string sort.35 min
  20. Async JavaScript: promises, await and fetchThe event loop, async and await, fetch with res.ok checks, Promise.all, and timeouts with AbortController.35 min
  21. Modules, Node and reading TypeScriptimport and export, package.json, classes, and types as notes the compiler checks, read through a small tool server.30 min
  22. A chat front end in the browserThe DOM and events, model text kept out of innerHTML, a streamed reply parsed from server-sent events, and a Stop button.40 min
  23. APIs with FastAPITyped routes, pydantic models, automatic validation and docs, tested with httpx.45 min
  24. Streaming from the serverServer-sent events written by a server: an ASGI app that sends a body in pieces, FastAPI's StreamingResponse, heartbeats, and what a closed connection looks like.40 min
  25. Project: a FastAPI service with accountsA session per request, bcrypt sign-ups, signed tokens, ownership checks and tests on a fresh database.45 min
  26. Serving a model behind FastAPILoad once with lifespan, a typed predict route, a batch route, a cap on work in flight, 429 with Retry-After, a readiness route and a 202 job.45 min
  27. Capstone: a streaming chat serviceA FastAPI service with key auth, a per-user bucket, a token budget, request ids and an event-stream reply, tested on fresh state.45 min
Step by step 9 steps

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.

Part of a free course 127 lessons

Free Python developer course

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.

Part of a free course 20 lessons

Build and Operate HTTP APIs

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