Designing REST APIs That Age Well

Designing REST APIs That Age Well in Python: FastAPI makes it trivial to expose a function over HTTP. It does not stop you exposing a bad one.

Concept Explanation

FastAPI makes it trivial to expose a function over HTTP. It does not stop you exposing a bad one. An API is a contract you will be maintaining for years, and the design decisions you make in the first hour are the ones you cannot undo without breaking every client.

Resources, Not Actions

The core REST idea: URLs name things (nouns), and HTTP verbs describe what you do to them.

Bad (verb in the URL)Good
POST /createUserPOST /users
GET /getUserById?id=5GET /users/5
POST /deleteOrderDELETE /orders/88
GET /users/5/updateEmailPATCH /users/5

Use plural nouns consistently (/users, not /user), and nest only to show ownership: /users/5/orders means "the orders belonging to user 5". Do not nest three levels deep — /users/5/orders/88/lines/2 should just be /order-lines/2.

The Verbs and Their Contracts

VerbPurposeSafeIdempotent
GETReadYesYes
POSTCreateNoNo
PUTReplace entirelyNoYes
PATCHUpdate some fieldsNoUsually
DELETERemoveNoYes

Idempotent means calling it five times has the same effect as calling it once. This matters more than it sounds: a mobile client on a bad connection retries. A retried PUT is harmless; a retried POST creates a second order. That is why payment APIs require an idempotency key on POST.

Safe means no side effects. A GET that deletes something will be triggered by every crawler and browser prefetch that finds the URL.

Status Codes That Mean Something

CodeWhen
200 OKSuccessful GET, PATCH, PUT
201 CreatedSuccessful POST — include a Location header
204 No ContentSuccessful DELETE
400 Bad RequestMalformed syntax
401 UnauthorizedNot authenticated (you are nobody)
403 ForbiddenAuthenticated but not allowed (you are somebody, just not this somebody)
404 Not FoundResource does not exist
409 ConflictViolates current state — duplicate email, already cancelled
422 Unprocessable EntitySyntax fine, validation failed (FastAPI's default)
429 Too Many RequestsRate limited — include Retry-After
500 Internal Server ErrorYour bug. Never send details to the client

Returning 200 {"error": "not found"} is the most common API design failure. It forces every client to parse the body to discover something the status line already had a way to say, and it breaks every retry policy, cache, and monitoring dashboard in the chain.

Pagination Is Not Optional

GET /orders must never mean "all 4 million orders". Two approaches:

StyleQueryProsCons
Offset?limit=50&offset=100Simple, jump to any pageSlow at depth; items shift as data changes
Cursor?limit=50&after=eyJpZCI6...Stable and fast at any depthCannot jump to page 47

Use cursors for anything large or frequently changing. Either way, return the total (or a next-page token) in the body so clients know when to stop.

Versioning

Put the version in the path — /v1/orders — from day one. It costs nothing now and is the only cheap way to make a breaking change later. Adding a field is not breaking; removing one, renaming one, or tightening validation is.

Errors Should Be Machine-Readable

{
  "error": {
    "code": "insufficient_stock",
    "message": "Only 2 units of WGT-0042 remain",
    "field": "lines.0.quantity",
    "request_id": "b3f1c9a2"
  }
}

A stable code lets clients branch on the failure; message is for humans; request_id is what turns a support ticket into a log search.


Code Example #1 (Basic)

The same endpoints, designed badly and then properly.

from fastapi import FastAPI, HTTPException, Response, status
from pydantic import BaseModel, EmailStr, Field

app = FastAPI(title="Users API", version="1.0.0")

_users: dict[int, dict] = {}
_next_id = 1


# ---------------------------------------------------------------
# BAD -- verbs in URLs, everything returns 200, no typed responses
# ---------------------------------------------------------------
@app.post("/createUser")
def create_user_bad(payload: dict):
    if "email" not in payload:
        return {"success": False, "error": "email required"}     # 200 for an error
    return {"success": True, "id": 1}


@app.get("/getUserById")
def get_user_bad(id: int):
    user = _users.get(id)
    if not user:
        return {"success": False, "error": "not found"}          # 200 again
    return user


# ---------------------------------------------------------------
# GOOD -- resource URLs, correct codes, separate in/out models
# ---------------------------------------------------------------
class UserCreate(BaseModel):
    email: EmailStr
    full_name: str = Field(min_length=2, max_length=80)
    password: str = Field(min_length=12)          # accepted, never returned


class UserRead(BaseModel):
    id: int
    email: EmailStr
    full_name: str                                # note: no password field


class UserPatch(BaseModel):
    email: EmailStr | None = None
    full_name: str | None = Field(default=None, min_length=2, max_length=80)


@app.post("/v1/users", response_model=UserRead, status_code=status.HTTP_201_CREATED)
def create_user(payload: UserCreate, response: Response):
    global _next_id
    if any(u["email"] == payload.email for u in _users.values()):
        raise HTTPException(status.HTTP_409_CONFLICT, "email already registered")

    user = {"id": _next_id, "email": payload.email, "full_name": payload.full_name}
    _users[_next_id] = user
    response.headers["Location"] = f"/v1/users/{_next_id}"       # where it now lives
    _next_id += 1
    return user


@app.get("/v1/users/{user_id}", response_model=UserRead)
def get_user(user_id: int):
    user = _users.get(user_id)
    if user is None:
        raise HTTPException(status.HTTP_404_NOT_FOUND, f"user {user_id} not found")
    return user


@app.patch("/v1/users/{user_id}", response_model=UserRead)
def update_user(user_id: int, payload: UserPatch):
    user = _users.get(user_id)
    if user is None:
        raise HTTPException(status.HTTP_404_NOT_FOUND, f"user {user_id} not found")
    # exclude_unset: only the fields the client actually sent
    user.update(payload.model_dump(exclude_unset=True))
    return user


@app.delete("/v1/users/{user_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_user(user_id: int):
    if _users.pop(user_id, None) is None:
        raise HTTPException(status.HTTP_404_NOT_FOUND, f"user {user_id} not found")
    return None                                    # 204 carries no body

exclude_unset=True is the detail that makes PATCH correct. Without it, every unsent field arrives as None and you overwrite the user's name with nothing.

Code Example #2 (Intermediate)

Pagination, filtering, structured errors, and idempotent creates.

import uuid
from datetime import datetime, timezone
from typing import Annotated, Literal

from fastapi import (APIRouter, Depends, FastAPI, Header, HTTPException,
                     Query, Request, Response, status)
from fastapi.responses import JSONResponse
from pydantic import BaseModel, Field

app = FastAPI(title="Orders API", version="1.0.0")
v1 = APIRouter(prefix="/v1", tags=["orders"])

_orders: dict[int, dict] = {
    i: {
        "id": i,
        "customer_id": (i % 7) + 1,
        "status": ["pending", "shipped", "cancelled"][i % 3],
        "total": round(15 + i * 3.5, 2),
        "created_at": datetime(2024, 5, 1, tzinfo=timezone.utc).isoformat(),
    }
    for i in range(1, 121)
}
_idempotency: dict[str, int] = {}       # key -> already-created order id


# ---------- Structured errors, applied globally ----------
class ApiError(Exception):
    def __init__(self, status_code: int, code: str, message: str, field: str | None = None):
        self.status_code, self.code, self.message, self.field = status_code, code, message, field


@app.exception_handler(ApiError)
async def api_error_handler(request: Request, exc: ApiError):
    body = {"error": {"code": exc.code, "message": exc.message,
                      "request_id": request.headers.get("x-request-id", str(uuid.uuid4())[:8])}}
    if exc.field:
        body["error"]["field"] = exc.field
    return JSONResponse(status_code=exc.status_code, content=body)


# ---------- Reusable pagination, as a dependency ----------
class Page(BaseModel):
    limit: int = Field(default=25, ge=1, le=100)
    offset: int = Field(default=0, ge=0)


def pagination(
    limit: Annotated[int, Query(ge=1, le=100, description="Items per page")] = 25,
    offset: Annotated[int, Query(ge=0)] = 0,
) -> Page:
    return Page(limit=limit, offset=offset)


class OrderRead(BaseModel):
    id: int
    customer_id: int
    status: str
    total: float
    created_at: str


class OrderList(BaseModel):
    items: list[OrderRead]
    total: int                     # how many match the filter overall
    limit: int
    offset: int
    next_offset: int | None        # null when this is the last page


class OrderCreate(BaseModel):
    customer_id: int = Field(gt=0)
    total: float = Field(gt=0)


# ---------- Collection: filter, sort, paginate ----------
@v1.get("/orders", response_model=OrderList)
def list_orders(
    page: Annotated[Page, Depends(pagination)],
    status_filter: Annotated[Literal["pending", "shipped", "cancelled"] | None,
                             Query(alias="status")] = None,
    customer_id: Annotated[int | None, Query(gt=0)] = None,
    sort: Annotated[Literal["created_at", "-created_at", "total", "-total"],
                    Query()] = "-created_at",
):
    rows = list(_orders.values())
    if status_filter:
        rows = [r for r in rows if r["status"] == status_filter]
    if customer_id:
        rows = [r for r in rows if r["customer_id"] == customer_id]

    key = sort.lstrip("-")
    rows.sort(key=lambda r: r[key], reverse=sort.startswith("-"))

    total = len(rows)
    window = rows[page.offset: page.offset + page.limit]
    nxt = page.offset + page.limit
    return OrderList(
        items=window, total=total, limit=page.limit, offset=page.offset,
        next_offset=nxt if nxt < total else None,
    )


@v1.get("/orders/{order_id}", response_model=OrderRead)
def get_order(order_id: int):
    order = _orders.get(order_id)
    if order is None:
        raise ApiError(status.HTTP_404_NOT_FOUND, "order_not_found",
                       f"No order with id {order_id}")
    return order


# ---------- Idempotent POST: a retry must not create a second order ----------
@v1.post("/orders", response_model=OrderRead, status_code=status.HTTP_201_CREATED)
def create_order(
    payload: OrderCreate,
    response: Response,
    idempotency_key: Annotated[str | None, Header(alias="Idempotency-Key")] = None,
):
    if idempotency_key and idempotency_key in _idempotency:
        existing = _orders[_idempotency[idempotency_key]]
        response.status_code = status.HTTP_200_OK      # not 201: nothing new was made
        response.headers["Location"] = f"/v1/orders/{existing['id']}"
        return existing

    new_id = max(_orders) + 1
    order = {
        "id": new_id,
        "customer_id": payload.customer_id,
        "status": "pending",
        "total": payload.total,
        "created_at": datetime.now(timezone.utc).isoformat(),
    }
    _orders[new_id] = order
    if idempotency_key:
        _idempotency[idempotency_key] = new_id
    response.headers["Location"] = f"/v1/orders/{new_id}"
    return order


# ---------- A state transition that is not simply "update a field" ----------
@v1.post("/orders/{order_id}/cancellation", response_model=OrderRead)
def cancel_order(order_id: int):
    order = _orders.get(order_id)
    if order is None:
        raise ApiError(status.HTTP_404_NOT_FOUND, "order_not_found",
                       f"No order with id {order_id}")
    if order["status"] == "shipped":
        raise ApiError(status.HTTP_409_CONFLICT, "already_shipped",
                       "A shipped order cannot be cancelled", field="status")
    order["status"] = "cancelled"
    return order


app.include_router(v1)


# ---------- Health check, unversioned by convention ----------
@app.get("/health", include_in_schema=False)
def health():
    return {"status": "ok", "orders": len(_orders)}

Two designs here are worth arguing about, so here is the reasoning. POST /orders/{id}/cancellation models cancellation as creating a sub-resource rather than PATCH-ing a status field — it makes the operation's preconditions explicit and gives it somewhere to return a proper 409. And the Idempotency-Key header is what every payment provider requires, because "the client retried and got charged twice" is a bug you only fix once.

Run it with:

uvicorn main:app --reload

then open http://127.0.0.1:8000/docs — every model, constraint, and status code above appears in the generated documentation without writing any.


Common Mistakes

  1. Verbs in URLs: /getUser, /createOrder. The verb belongs in the HTTP method.
  2. Returning 200 with an error body: breaks retries, caching, and monitoring. Use the status line.
  3. No pagination on collections: works with 50 rows in development, times out with 4 million in production.
  4. Exposing internal fields: returning the password hash or an internal cost column because you reused the database model as the response model.
  5. PATCH that overwrites unsent fields with None: use model_dump(exclude_unset=True).
  6. No versioning: the first breaking change forces every client to update simultaneously.
  7. Leaking exception details in a 500: stack traces tell an attacker your file layout and library versions. Log them; return a request id.
  8. Confusing 401 and 403: 401 means "log in", 403 means "logged in, still not allowed".
  9. Non-idempotent POST with no idempotency key: a retried request creates duplicates.
  10. Inconsistent naming: /users and /Order and /api/v1/items in the same service. Pick one convention.
  11. Returning a bare array: [...] leaves nowhere to add pagination metadata later. Wrap it in an object from the start.
  12. Deep nesting: /a/1/b/2/c/3 is a URL nobody can construct or cache. Flatten it.

Best Practices

  • Nouns in URLs, verbs in methods, plural and consistent.
  • Version from day one with /v1 — it is free now and expensive to retrofit.
  • Separate request and response models: OrderCreate, OrderRead, OrderPatch. Never expose an ORM model directly.
  • Return the right status code, and 201 with a Location header on create.
  • Paginate every collection, with a default limit and a hard maximum.
  • Return structured errors with a stable machine-readable code and a request_id.
  • Support Idempotency-Key on POST for anything that costs money or cannot be duplicated.
  • Use Query and Path with constraints so validation and documentation come from the same declaration.
  • Group routes with APIRouter and a prefix rather than repeating the version in every decorator.
  • Add a /health endpoint outside the version prefix for load balancers.
  • Treat additions as safe and removals as breaking: adding an optional field needs no new version; removing one does.
  • Document the contract in the code — response models, constraints, and descriptions all flow into OpenAPI automatically.

Practice Exercises

  1. The Redesign: Take these four endpoints — POST /addBook, GET /findBook?id=3, POST /removeBook, GET /listAllBooks — and rewrite them as proper REST routes with correct verbs, paths, and status codes. Explain each change in a comment.
  2. The Paginated Collection: Build a GET /v1/items endpoint with limit, offset, a status filter, and a sort parameter, returning an object containing items, total, and next_offset. Confirm in /docs that the constraints appear.
  3. The Idempotency Test: Implement POST with an Idempotency-Key header, then call it twice with the same key and once with a different one. Show that you get 201, 200, and 201 respectively, and that only two resources exist.