Skip to content
Index Ai Academy
Phase 8 · Building APIs

Designing a REST API

Resources, methods, status codes, errors and pagination done well.

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

What it covers7

First principles

How does a client continue a long list without asking for everything at once?

A paginated list returns a bounded set of resources and a marker for where to resume. A stable ordering makes that marker meaningful on the next request.

  1. Starting point

    Reviews are ordered by created time and ID

  2. What changes

    Return the first page with a cursor for its final review

  3. Result

    The next request resumes after that review

Compare all three steps
  1. Starting point

    Reviews are ordered by created time and ID

  2. What changes

    Return the first page with a cursor for its final review

  3. Result

    The next request resumes after that review

Complete and reverse the trace

Given Reviews are ordered by created time and ID and The next request resumes after that review, write down the missing step that connects them.

Compare with the worked step

Return the first page with a cursor for its final review

Now take Return the first page with a cursor for its final review and the result above. Write an input and an implementation that could produce this trace.

Check one starting point

Reviews are ordered by created time and ID. Check that your implementation produces the result shown above.

Try it on a new case

Two reviews have the same timestamp. Why put the ID in the cursor too?

Show worked reasoning

The ID breaks the tie. A cursor using only the timestamp cannot distinguish which equal-time rows were already returned.

Run, change, and build

Check this when debugging. Returning 200 with an error object in the body.

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. Two reviews have the same timestamp. Why put the ID in the cursor too?

Why it matters

An API is a user interface for programmers, and now for AI agents too. A well-designed one can be used correctly from a glance at one example. A badly designed one causes bugs in every program that calls it. Those bugs are hard to fix later, since once people depend on your API, every change risks breaking them. The habits here are the ones behind APIs people praise, like Stripe's and Anthropic's.

What you'll be able to do

  • Name resources and routes so developers can guess them
  • Pick status codes precisely, and return errors in one consistent shape
  • Explain safe and idempotent methods, and why retries depend on them
  • Implement cursor pagination that stays correct while data changes
  • Answer a long job with 202 and a status resource the client can poll
Quick check
A client sends a request to create a new review, and it succeeds. Which status code fits best?
  1. 302 Found
  2. 204 No Content
  3. 201 Created
  4. 200 OK
Show the answer

201 Created

201 says something new was made, and the response usually includes it and where it lives. Status codes that say exactly what happened let clients react without reading the body.

The idea: guessable names, safe repeats and a bookmark

This rests on API styles: REST names things with nouns and uses the verbs for actions. Design is the set of rules that make one example enough to guess the rest.

Names a developer can guess

In a well-run supermarket, you can find the pasta in a store you've never visited. The signs follow rules you already know. A good API works the same way, so once someone has seen one address, they can guess the rest:

  • Plural nouns for collections: /campaigns, /orders. One item lives under its collection: /campaigns/cmp_103.
  • Lowercase, with hyphens between words: /gift-cards, not /GiftCards or /gift_cards.
  • Nest one level, at most, for true ownership: /customers/c_42/orders. Deeper nesting gets unwieldy, so use filters instead: /orders?customer=c_42.
  • Ids as opaque strings with a prefix, such as cmp_103 or ord_9xK2. A prefix tells a person what kind of thing an id is at a glance. Opaque means nobody should read meaning into the rest, which leaves you free to change how ids are made later.
  • Actions that don't fit a method become a sub-resource: POST /campaigns/cmp_103/pause.
Quick check
By these rules, which address is right for one customer's orders?
  1. /customers/c_42/orders
  2. /Customers/c_42/Orders
  3. /getOrdersForCustomer?id=42
  4. /customer/c_42/order
Show the answer

/customers/c_42/orders

Plural nouns, lowercase, nested one level for true ownership.

Safe and idempotent methods

Pressing the elevator button twice doesn't call two elevators. Putting an item in your cart twice can mean you buy two. The first is idempotent, a long word for "repeating it is harmless". The second isn't.

A related idea is safe, meaning "changes nothing at all", like reading a menu. Together, these two properties decide what a client may repeat:

methodsafe (changes nothing)?idempotent (repeating is harmless)?
GETyesyes
PUTnoyes: the second PUT sets the same values again
DELETEnoyes: the item is gone either way
PATCHnousually, for "set" changes; not for "add 1"
POSTnono: two POSTs can create two orders
Quick check
From the lesson on API styles: PUT replaces the whole resource, and PATCH changes only the fields that are sent. What does this print when each gets a body that holds only a budget?
campaign = {"name": "Spring", "budget": 500}

def put(resource, body):
    return dict(body)

def patch(resource, body):
    merged = dict(resource)
    merged.update(body)
    return merged

print(put(campaign, {"budget": 800}), patch(campaign, {"budget": 800}))
  1. {'name': 'Spring', 'budget': 800} {'budget': 800}
  2. {'budget': 800} {'budget': 800}
  3. {'name': 'Spring', 'budget': 800} {'name': 'Spring', 'budget': 800}
  4. {'budget': 800} {'name': 'Spring', 'budget': 800}
Show the answer

{'budget': 800} {'name': 'Spring', 'budget': 800}

PUT takes the body as the whole new resource, so the name is gone. PATCH copies the old resource and changes the one field that was sent. Rules like this are what a client relies on when it guesses how your API behaves, and this lesson is about making those guesses come true.

Quick check
A client's request times out, and it can't tell whether the server acted. Which request is safe to send again as it is?
  1. A PATCH that adds 1 to a counter
  2. None of them: no request is ever safe to repeat
  3. POST /orders to place the order
  4. PUT /campaigns/cmp_103 with the full new settings
Show the answer

PUT /campaigns/cmp_103 with the full new settings

PUT is idempotent: setting the same values twice leaves the same result. The other two could create a second order or count twice.

Try it now

A retried PUT changes nothing more. A retried POST makes a second thing, unless it carries an idempotency key.

Quick check
What does this print?
balance = 100
def set_balance(v):
    global balance
    balance = v
set_balance(50)
set_balance(50)
print(balance)
  1. 50
  2. 150
  3. 0
  4. 100
Show the answer

50

The first call sets balance to 50, and the second sets it to 50 again, so it prints 50. Doing it twice has the same effect as doing it once. That's what idempotent means, and it's why PUT can be retried.

Quick check
A client sends DELETE /orders/ord_5, the network drops the response, and the client sends it again. What should the API do?
  1. Restore the order and then delete it again, so the second request did its job too
  2. Treat it as harmless: the order stays deleted (answer 204, or 404 if you report it's already gone)
  3. Answer 500, since deleting something that's already gone is a server error
  4. Delete the next order in the list instead, since ord_5 has already been deleted
Show the answer

Treat it as harmless: the order stays deleted (answer 204, or 404 if you report it's already gone)

DELETE is idempotent: after one or ten calls the order is gone. Either answer is fine, as long as nothing else changes.

Status codes, precisely

Think of the status code as a stamp on a returned letter. The first digit says whose problem it is:

  • 2xx: it worked.
  • 4xx: the client must change something. Sending the same thing again won't help.
  • 5xx: the server failed, and a retry might work.

These codes cover nearly every case:

codeuse it when
200 OKa read or update worked
201 Createda POST created something; add a Location header pointing at it
202 Acceptedthe work was queued and will finish later
204 No Contentit worked and there's nothing to send back (often DELETE)
400 Bad Requestthe request is malformed: bad JSON, a body that can't be parsed
401 Unauthorizedno credentials, or credentials that don't work
403 Forbiddenthe credentials work, but aren't allowed to do this
404 Not Foundno such resource (also used to avoid revealing one exists)
409 Conflictit clashes with current state: a duplicate email, an order that has already shipped
412 Precondition Failedthe client's If-Match names a version that's no longer current
422 Unprocessable Contentwell-formed, but the values fail the rules: a missing required field, a negative budget
429 Too Many Requestsrate limited; say when to retry with Retry-After
500 Internal Server Errora bug on the server
503 Service Unavailableoverloaded or down for maintenance; retry later
Quick check
A request is queued, and the work will finish later. Which status fits?
  1. 201 Created
  2. 202 Accepted
  3. 204 No Content
  4. 200 OK
Show the answer

202 Accepted

202 says the request was taken in and nothing has been done yet.

For a request that is valid JSON but whose values break the rules, such as a negative budget, 422 Unprocessable Content fits best, though some APIs use 400 for all input errors. Never answer 200 with {"error": ...} inside. Clients, monitoring and retry logic all read the status code first, so they'd count the failure as a success.

One error shape, everywhere

If every department of a company sent complaints on a different form, nobody could process them. So pick one error format and use it for every endpoint. Here's Anthropic's:

{
  "type": "error",
  "error": {"type": "not_found_error", "message": "model: claude-opus-9 not found"}
}

A machine-readable type lets code branch on it, and a human message says what to fix. Many APIs add a param naming the bad field. There's also an internet standard, problem details (RFC 9457), with type, title, status and detail fields. Which one you choose matters less than using it everywhere.

Quick check
A valid API key tries to delete another company's campaign. Which status fits best?
  1. 401 Unauthorized, since the key isn't allowed to do it
  2. 500 Internal Server Error, since the delete didn't happen
  3. 403 Forbidden, or 404 to avoid revealing the campaign exists
  4. 400 Bad Request, since the request asks for something wrong
Show the answer

403 Forbidden, or 404 to avoid revealing the campaign exists

401 means the credentials themselves failed. Here they're valid but not allowed this action: 403. Many APIs return 404 so outsiders can't probe which ids exist.

Filtering, sorting and pagination

Lists need options, passed as query parameters: GET /orders?status=paid&sort=-created&limit=20. A leading - for descending order is a common convention.

Never return an unbounded list. One day that list has a million rows. Pagination returns a page at a time, and there are two main ways.

Offset pagination (?offset=40&limit=20) means "skip 40, then give me 20". It's like saying "start at line 40". That's simple, but it breaks when data changes between pages. If a new order arrives while you read, every line shifts down by one, and one order appears on two pages:

The cell in the Python part runs this: a new order arrives between two pages, and one order shows up twice.

Large offsets are also slow, because the database still counts past every skipped row.

Cursor pagination is a bookmark. A bookmark marks where you stopped, however many pages get added before it. Each page of results ends with a next_cursor: a token that says where you stopped, such as the sort key of the last item. The next request asks for items after that point. New items can't shift anything, and the database can jump straight there with an index. The response looks like this:

{
  "data": [ ... ],
  "has_more": true,
  "next_cursor": "eyJhZnRlciI6IFsxNzMwLCAib3JkXzkiXX0"
}

Make the cursor opaque: encode it, so clients pass it back without building or editing it. Then you're free to change what's inside.

In your own words
Why is a retried PUT harmless and a retried POST not, and why does a cursor beat an offset?

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

In Python: cursors, error shapes and a job with a status page

First the offset bug, run for real, then the cursor that avoids it.

Setup (runs before every cell) · 3 lines

The lesson runs this once, before its first cell, and every cell, drill and example starts with what it defines. A cell that changes a setup object changes it for the cells after it, until the page reloads.

import requests

BASE = "https://api.gradient.test"
orders = [f"order {n}" for n in range(10, 0, -1)]      # newest first
page1 = orders[0:4]
orders.insert(0, "order 11")                            # a new order arrives
page2 = orders[4:8]
print("page 1:", page1)
print("page 2:", page2)                                 # "order 7" appears twice
It runs right here in your browser, with nothing to install.

Now the cursor fix. A cursor says where you stopped: the sort key of the last item. The next page asks for items after that point.

Uses the setup above, 3 lines.

orders = [f"order {n}" for n in range(10, 0, -1)]      # newest first

def page_after(rows, cursor, size):
    start = 0 if cursor is None else rows.index(cursor) + 1
    page = rows[start:start + size]
    return page, (page[-1] if len(page) == size else None)

page1, cursor = page_after(orders, None, 4)
orders.insert(0, "order 11")                            # a new order arrives
page2, cursor = page_after(orders, cursor, 4)
print("page 1:", page1)
print("page 2:", page2)                                 # no repeat
Worked example

An opaque cursor

A cursor is often JSON encoded with URL-safe base64. Base64 turns any bytes into letters, digits, - and _, which are safe in a URL.

Uses the setup above, 3 lines.

import base64, json

def encode_cursor(position):
    raw = json.dumps({"after": position}).encode()
    return base64.urlsafe_b64encode(raw).decode().rstrip("=")

def decode_cursor(cursor):
    # put back the padding we removed
    padded = cursor + "=" * (-len(cursor) % 4)
    return json.loads(base64.urlsafe_b64decode(padded))["after"]

c = encode_cursor([1730, "ord_9"])
print(c)
print(decode_cursor(c))
In the lesson you can change this and run it.

Base64 isn't encryption: anyone can decode it, so never put secrets in a cursor. It only signals "don't build this yourself". The = padding is stripped to keep URLs tidy and added back before decoding. Sorting by a time and the id matters. Two items can share a timestamp, and the id breaks the tie so no item is ever skipped.

Drill

One error shape

Write error_response(status, code, message, details=None): return (status, body) where body is always {"error": {"code": code, "message": message}}, with a "details" key inside error only when details are given. Raise ValueError if status is below 400: success responses aren't errors.

Uses the setup above, 3 lines.

def error_response(status, code, message, details=None):
    return status, {"message": message}


print(
    error_response(422, "invalid_field", "budget must be positive", {"field": "budget"})
)
In the lesson, your code is checked as you write it.

Versioning

Adding a dish to a menu upsets nobody. Taking away someone's usual order does. APIs work the same way.

Some changes are additive: a new endpoint, a new optional field, a new field in responses. Well-behaved clients ignore fields they don't know, so additive changes don't break anyone. Removing or renaming a field, changing a type or tightening a rule is breaking.

Breaking changes need a new version. There are two common styles:

  • A version in the URL: /v1/campaigns, /v2/campaigns. It's easy to see and to route.
  • A version in a header, often a date: the Claude API's anthropic-version: 2026-10-21. Each client keeps the behavior of the date it pinned, until it opts into a newer one.

Either way, keep old versions running long enough for clients to move, and announce removals well in advance.

Drill

Is this change breaking?

Write breaking_changes(old, new): old and new map each response field to its type. Return a sorted list of problems: "removed: FIELD" for fields that disappeared and "type changed: FIELD" for fields whose type changed. Added fields aren't breaking, since well-behaved clients ignore what they don't know.

Uses the setup above, 3 lines.

OLD = {"id": "string", "budget": "integer", "status": "string", "owner": "string"}
NEW = {"id": "string", "budget": "string", "status": "string", "currency": "string"}


def breaking_changes(old, new):
    return []


print(breaking_changes(OLD, NEW))
In the lesson, your code is checked as you write it.

A long job: 202, a status resource and a poll

Some requests cannot finish while the client waits: a batch of model calls, an export, a retraining run. The API accepts the work, answers 202 Accepted with a job id and a Location header, and the client polls a status resource until it is done. The cell runs the idea with a dictionary as the queue.

Uses the setup above, 3 lines.

JOBS = {}

def start_job(body):
    job_id = f"job_{len(JOBS) + 1}"
    JOBS[job_id] = {"status": "queued", "polls": 0, "input": body}
    return 202, {"Location": f"/jobs/{job_id}"}, {"id": job_id, "status": "queued"}

def get_job(job_id):
    job = JOBS.get(job_id)
    if job is None:
        return 404, {}, {"error": {"code": "not_found"}}
    job["polls"] += 1
    if job["polls"] >= 3:
        job["status"] = "done"
    return 200, {}, {"id": job_id, "status": job["status"]}

status, headers, body = start_job({"documents": 40})
print(status, headers["Location"], body)
for _ in range(3):
    print(get_job(body["id"])[2])

The first two polls say queued and the third says done. The status resource is what lets a client wait without holding a connection open, and the 202 is the honest answer: the work was taken in, and nothing has been done yet.

In your own words
What does a client get back when it starts a long job, and what does it do next?

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

In AI and ML systems: a provider's API is an API like yours

Every habit in this lesson shows up in the model APIs you call. Their error shape is one body for every failure, with a type your code can branch on. Their status list is the one in the table: 401 for a bad key, 403 for a key without permission, 429 with a Retry-After, 529 when the service is overloaded. Their list endpoints page with a cursor, not an offset, because the list grows while you read it. And a batch of model calls is a long job, so it is accepted first and polled for its result. Read a provider's docs with this lesson's table beside you and most of it is already familiar.

Uses the setup above, 3 lines.

page = requests.get(f"{BASE}/v1/customers", params={"limit": 3, "offset": 0}).json()
print(page["count"], len(page["data"]), sorted(page["data"][0])[:4])

The practice customers route pages by limit and offset, which is fine for a table that does not change while you read it. A list a model provider serves, such as its list of models or batches, takes a limit and an id to start after (after_id) and tells you whether there is more (has_more), which is the cursor pattern with the id as the cursor.

Where this shows up in an engineer's week

Three reviews return again and again. "Why is this a 200 with an error inside?" Clients and monitors count it as a success; change it to a status. "Why does the page repeat rows?" The list is paged by offset while rows arrive. "Why did the mobile app break after the release?" A field was renamed inside a version. Each is a rule from this lesson. Goes deeper in: Documenting APIs with OpenAPI writes the design down as a spec, Validating requests with schemas checks the bodies, and Build a server: tools turns routes like these into tools for a model.

In your own words
What in a model provider's API is the same as the design rules in this lesson?

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

  • 5 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

Which method is NOT idempotent?

  1. POST
  2. PUT
  3. DELETE
  4. GET

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