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.
Resources, methods, status codes, errors and pagination done well.
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.
Reviews are ordered by created time and ID
Return the first page with a cursor for its final review
The next request resumes after that review
Reviews are ordered by created time and ID
Return the first page with a cursor for its final review
The next request resumes after that review
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.
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.
Reviews are ordered by created time and ID. Check that your implementation produces the result shown above.
Two reviews have the same timestamp. Why put the ID in the cursor too?
The ID breaks the tie. A cursor using only the timestamp cannot distinguish which equal-time rows were already returned.
Check this when debugging. Returning 200 with an error object in the body.
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.
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.
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.
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:
/campaigns, /orders. One item lives under its collection: /campaigns/cmp_103./gift-cards, not /GiftCards or /gift_cards./customers/c_42/orders. Deeper nesting gets unwieldy, so use filters instead: /orders?customer=c_42.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.POST /campaigns/cmp_103/pause./customers/c_42/orders
Plural nouns, lowercase, nested one level for true ownership.
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:
| method | safe (changes nothing)? | idempotent (repeating is harmless)? |
|---|---|---|
| GET | yes | yes |
| PUT | no | yes: the second PUT sets the same values again |
| DELETE | no | yes: the item is gone either way |
| PATCH | no | usually, for "set" changes; not for "add 1" |
| POST | no | no: two POSTs can create two orders |
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})){'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.
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.
A retried PUT changes nothing more. A retried POST makes a second thing, unless it carries an idempotency key.
balance = 100 def set_balance(v): global balance balance = v set_balance(50) set_balance(50) print(balance)
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.
DELETE /orders/ord_5, the network drops the response, and the client sends it again. What should the API do?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.
Think of the status code as a stamp on a returned letter. The first digit says whose problem it is:
These codes cover nearly every case:
| code | use it when |
|---|---|
| 200 OK | a read or update worked |
| 201 Created | a POST created something; add a Location header pointing at it |
| 202 Accepted | the work was queued and will finish later |
| 204 No Content | it worked and there's nothing to send back (often DELETE) |
| 400 Bad Request | the request is malformed: bad JSON, a body that can't be parsed |
| 401 Unauthorized | no credentials, or credentials that don't work |
| 403 Forbidden | the credentials work, but aren't allowed to do this |
| 404 Not Found | no such resource (also used to avoid revealing one exists) |
| 409 Conflict | it clashes with current state: a duplicate email, an order that has already shipped |
| 412 Precondition Failed | the client's If-Match names a version that's no longer current |
| 422 Unprocessable Content | well-formed, but the values fail the rules: a missing required field, a negative budget |
| 429 Too Many Requests | rate limited; say when to retry with Retry-After |
| 500 Internal Server Error | a bug on the server |
| 503 Service Unavailable | overloaded or down for maintenance; retry later |
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.
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.
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.
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.
Write a sentence or two, then compare it with a good answer in the lesson.
First the offset bug, run for real, then the cursor that avoids it.
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
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
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))
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.
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"}) )
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:
/v1/campaigns, /v2/campaigns. It's easy to see and to route.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.
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))
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.
Write a sentence or two, then compare it with a good answer in the lesson.
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.
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.
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.
Which method is NOT idempotent?
575 lessons in thirteen phases. 176 are free without an account, and a free account opens the rest. See every lesson.
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