Skip to content

Designing and building APIs

Phase 2 · The web and APIs · 15 min read

What you'll be able to do

  • Design endpoints whose methods, URLs, and JSON shapes tell callers what to expect.
  • Choose pagination, error, and retry behavior that remains predictable as data and traffic change.
  • Wrap a model behind a versioned contract and test that contract without a running server.

Start with the caller's contract

An API is an agreement between programs. The caller needs to know what it can send, receive, and expect on failure. An internal Python object is not automatically a good public response: changing its class or database columns should not force clients to change.

For ordinary data, default to resources (things) at noun URLs, with HTTP methods as verbs. A collection is plural: /predictions; one item is /predictions/p_42. Keep nesting shallow. /users/u_7/predictions/p_42 can express ownership, but chains of parent IDs make URLs brittle. Use query parameters for collection views: /predictions?status=done&sort=-created_at.

Resource-style routes: the noun is in the URL, the verb is the HTTP method.

RPC-style APIs name operations such as /predictions:rerun. Pick one when the action is the main concept and does not fit create/read/update/delete.

GraphQL lets callers request selected fields across related data through a schema, at the price of query-cost, caching, and access-control decisions.

Methods and message shapes

HTTP method semantics matter because clients and intermediaries act on them. GET reads and is safe: it should not cause an intended state change. GET, PUT, and DELETE are idempotent: repeating the same request should have the same intended effect as sending it once. POST usually creates or starts work and is not inherently idempotent. PATCH changes selected fields; whether a particular patch is idempotent depends on its instructions. PUT replaces the addressed resource, so a missing field may be cleared. DELETE removes it; a second deletion may return a different status while the final state stays absent. These properties extend the HTTP basics in Networking, DNS and HTTP.

JSON is a common wire format. Pick one field style, such as snake_case. Represent IDs as strings even if they are database integers; callers should not perform arithmetic on them. Use ISO 8601 timestamps with a timezone, for example 2026-11-21T09:30:00Z. State which fields may be absent or null, and whether unknown request fields are rejected.

{"id":"p_42","status":"done","created_at":"2026-11-21T09:30:00Z"}

A bare object suffices for one resource; an envelope such as {"data": ..., "next_cursor": ...} carries list metadata. Choose once and document it. Expose product concepts, not ORM objects, prompt templates, paths, or stack traces.

Errors and large collections

An error has two parts: an HTTP status for generic handling and a predictable body for the caller. A useful shape is {"error":{"code":"invalid_input","message":"Prompt is too long","details":{"field":"prompt"},"request_id":"r_17"}}. code is a stable machine value; message helps a person; details points to the bad input; request_id lets an operator find the matching log. Never put an error inside a 200 OK response. Use 400 for a malformed request, or 422 for a well-formed request that fails field validation; choose one validation convention consistently. Use 404 for a missing resource, 409 for a conflicting write, and 429 for a rate limit, often with Retry-After.

Unbounded GET /predictions eventually becomes slow and expensive. With offset pagination, offset=20&limit=20 skips the first 20 results. If a new item arrives at the front between page requests, the old item at position 20 shifts to 21 and can appear twice. A cursor instead means "continue after this stable sort key." For newest-first items, a cursor after p_42 should keep the next page after p_42 even if newer items arrive. Make the token opaque to callers, define a deterministic sort order with a tie breaker, and cap the page size. Document what happens when a cursor expires.

Filtering (status=done) and sorting (sort=-created_at) need documented allowed fields and a stable tie breaker. Bulk creation needs a stated size limit and a rule for partial failures: all or nothing, or a result per item. For example, 100 items at a maximum of 20 per request take 100 / 20 = 5 requests.

Retries, limits, and long work

Networks fail after the server has accepted a write but before the client sees the reply. A client retrying POST /charges could create a second charge. An Idempotency-Key lets the client name one logical operation. Suppose the first request with key k7 and payload fingerprint A creates charge c_9, then its response is lost. A retry with k7 and A returns the saved result for c_9 without running the charge again. Reusing k7 with fingerprint B is a conflict. Scope keys to the caller and define an expiry. Commit the side effect and the idempotency record in one transaction when possible. For an external charge, pass an idempotency key to the payment system and reconcile uncertain outcomes; saving a local result alone cannot guarantee one charge. See Delivery guarantees and idempotency for the deeper failure cases.

Set server and client timeouts, and publish rate limits so callers can budget and back off. Give each request an ID and put it in responses and logs. The API must say which endpoints require credentials; Authentication and authorization covers the mechanisms.

If inference may take longer than a normal request timeout, accept the job with 202 Accepted, return a status resource such as /jobs/j_8, and let the caller poll until it is done or failed. A 202 means accepted, not completed.

Evolve the contract and show how to call it

Adding an optional response field is usually compatible; removing or renaming a field, changing its type, or making an optional request field required breaks callers. Silently accepting misspelled request fields can hide bugs. Choose one version strategy, such as /v1/predictions or a version header. Publish when an old version will stop working, and give callers a migration path.

Documentation is part of the API: an OpenAPI description records paths, schemas, and statuses, and examples show successful and failed requests. Contract tests send representative inputs and assert the promised status and JSON shape. Run them when changing the service so accidental breaking changes appear before release.

The following FastAPI snippet is an illustration; the lab uses only the Python standard library. It shows a typed request, a path parameter, a query parameter, dependency injection, a creation status, and a handled missing item. A real service would persist data and apply one shared error handler. Check the FastAPI documentation for current details.

import uuid

from fastapi import Depends, FastAPI, Query, status
from fastapi.responses import JSONResponse
from pydantic import BaseModel, Field

app = FastAPI()
items = {}

class PredictionIn(BaseModel):
    text: str = Field(min_length=1, max_length=2000)

def caller_id() -> str:
    return "demo-caller"  # Replace with authentication.

@app.post("/predictions", status_code=status.HTTP_201_CREATED)
def create_prediction(body: PredictionIn, caller: str = Depends(caller_id)):
    item_id = f"p_{uuid.uuid4().hex}"
    items[item_id] = {"id": item_id, "status": "done",
                      "model": "baseline", "owner": caller}
    return {"id": item_id, "status": "done"}

@app.get("/predictions/{item_id}")
def get_prediction(item_id: str, include_model: bool = Query(False),
                   caller: str = Depends(caller_id)):
    item = items.get(item_id)
    if item is None or item["owner"] != caller:
        return JSONResponse(status_code=404, content={"error": {
            "code": "not_found", "message": "Prediction not found",
            "details": {}, "request_id": None}})
    return {k: v for k, v in item.items()
            if k != "owner" and (include_model or k != "model")}

For AI engineers

For AI engineers

A training script may trust its own input types; a public model endpoint cannot. Validate prompt type and maximum length before allocating expensive compute. Decide whether streaming partial output is useful. For slow jobs, use 202 and polling. Version the API schema separately from the model revision so a weight update does not silently rewrite client code. Return useful metadata, such as model revision and calibrated confidence when meaningful, with a defined schema. Tool-calling schemas are API contracts too: JSON Schema tells the model what arguments a tool accepts, but your server must still validate them. Do not expose raw internal prompts as an API field.

Common mistakes

  • Putting verbs in resource URLs (/getUser) while also relying on HTTP methods.
  • Using offsets on a changing feed without explaining duplicates or missed items.
  • Returning stack traces, internal model prompts, or inconsistent error shapes to callers.
  • Removing or renaming a field in a minor release and assuming clients will adapt.
  • Retrying payment-like POST requests without an idempotency key and payload check.
  • Returning huge lists or allowing unbounded batch sizes.

Check yourself

A client fetches page one, then a new prediction is inserted at the front. What can happen with offset pagination, and how does a cursor help?

The old final item on page one shifts to the next offset and can appear again. A cursor continues after the last seen stable sort key, so a new item before it does not shift the continuation point.

A create request succeeds, but its response times out. The client retries with the same idempotency key and a different body. What should the server do?

Reject the conflicting reuse of the key. A replay with the same payload fingerprint should return the saved result without creating another resource.

Your API changes score from a number to a string while keeping the same version. Is that additive?

No. Callers that parse or compare a number can break. Keep the old field contract or introduce a versioned change with a migration plan.

Model inference takes longer than the client timeout. Which response and follow-up resource fit the contract?

Return 202 Accepted with a job identifier and status URL. The client polls the status resource for completion or failure instead of treating acceptance as a final prediction.

Lab

Build the request-contract logic in code/api-design/ without a web server. Implement consistent errors, version negotiation, payload validation, cursor pagination, and a thread-safe idempotent write. Read the README for each function's contract (the cursor anchors on an item ID, a simplification); work in starter/lab.py. Run cd code/api-design && PYTHONPATH=starter python -m pytest tests -q. Your work is done when every test passes, including empty pages, exact error sets, and concurrent replays.

Go deeper