🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Designing a REST API: Status Codes, Auth, and Rate Limits

Python APIđŸŸĸ Free Lesson

Designing a REST API: Status Codes, Auth, and Rate Limits

An API is a contract that outlives the code that wrote it. Clients are generated from it, mobile apps ship with it baked in, and every ambiguity you leave in a status code or an error body becomes a permanent special case in someone else's retry logic. This lesson builds a small service that gets the boring decisions right: resource-shaped URLs, statuses that carry meaning, one parseable error envelope, safe token authentication, and limits that protect the shared dependency underneath.

What You'll Learn

  • 1Model resources with verbs and status codes that clients can branch on
  • 2Return one consistent error shape from every failure path
  • 3Implement JWT authentication without the classic algorithm and expiry mistakes
  • 4Add pagination, idempotency, and rate limiting to protect the service

Resources first, routes second

Designing endpoints by listing verbs on a controller produces URLs like /getUser and /deleteItemById, which then need a different path for bulk operations, filtering, and paging. Designing around resources produces a small, regular surface: a collection endpoint that supports create and list, and an item endpoint that supports read, replace, and delete. Filtering, sorting, and paging become query parameters on the collection rather than new routes.

VerbCollectionItemSuccessNotes
GETList with filtersFetch one200Never mutates; safe to retry
POSTCreateAction on the resource201 + LocationNot idempotent by default
PUTNot allowedFull replace200 or 204Idempotent
PATCHNot allowedPartial update200Define merge semantics
DELETENot allowedRemove204Repeatable: second call is also 204 or 404
HEADExistence checkExistence check200Useful for caches and clients

Status codes carry half the contract. 400 means the client sent something malformed, 401 means "who are you", 403 means "I know who you are and the answer is no", 409 means the request conflicts with current state, 422 is semantically invalid, and 429 means back off. Returning 200 with an {"error": ...} body forces every client to parse the body before it can decide whether to retry, which is precisely what status codes exist to avoid.

Status codes the client can branch on

python
from fastapi import FastAPI, HTTPException, Response, status
from pydantic import BaseModel

app = FastAPI()
ITEMS: dict[str, dict] = {}


class ItemIn(BaseModel):
    name: str
    price: float


@app.post("/items", status_code=status.HTTP_201_CREATED)
def create_item(payload: ItemIn, response: Response):
    item_id = payload.name.lower().replace(" ", "-")
    if item_id in ITEMS:
        raise HTTPException(status_code=409, detail="item already exists")
    ITEMS[item_id] = payload.model_dump()
    response.headers["Location"] = f"/items/{item_id}"
    return ITEMS[item_id]


@app.get("/items")
def list_items(limit: int = 20, offset: int = 0):
    if limit < 1 or limit > 100:
        raise HTTPException(status_code=400, detail="limit must be 1..100")
    page = list(ITEMS.values())[offset:offset + limit]
    return {"items": page, "total": len(ITEMS), "limit": limit, "offset": offset}


@app.get("/items/{item_id}")
def get_item(item_id: str):
    if item_id not in ITEMS:
        raise HTTPException(status_code=404, detail="item not found")
    return ITEMS[item_id]


@app.delete("/items/{item_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_item(item_id: str):
    ITEMS.pop(item_id, None)
    return Response(status_code=status.HTTP_204_NO_CONTENT)

The create endpoint returns 409 rather than overwriting, because a duplicate create that silently replaces data is how clients lose updates. The list endpoint returns a envelope with total, limit, and offset so a client can render a pager without a second call. And delete returns 204 with an empty body, so a retry of a delete that already succeeded is still a success rather than an error the client must special-case.

One error shape for every failure

Clients should be able to write a single interceptor that logs, displays, and retries failures. That is only possible if every error — validation, not found, rate limited, unexpected — arrives in the same structure.

python
from fastapi import FastAPI, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from fastapi import HTTPException

app = FastAPI()


@app.exception_handler(RequestValidationError)
async def validation_handler(request: Request, exc: RequestValidationError):
    return JSONResponse(
        status_code=422,
        content={"error": {"code": "validation_failed",
                           "message": "request body is invalid",
                           "fields": [{"loc": e["loc"], "msg": e["msg"]}
                                      for e in exc.errors()]}},
    )


@app.exception_handler(HTTPException)
async def http_handler(request: Request, exc: HTTPException):
    return JSONResponse(
        status_code=exc.status_code,
        content={"error": {"code": str(exc.status_code).lower(),
                           "message": exc.detail}},
    )


@app.get("/boom")
def boom():
    raise RuntimeError("database is on fire")

The last route exists to make a point: without a catch-all handler, an unexpected exception becomes an HTML stack trace or a bare 500 with no correlation id, and the client cannot tell the operator which request failed. Add a final handler that returns a generic 500 plus an id you have logged server-side, and never let exception text reach the caller — it routinely contains query fragments and file paths.

JWT authentication without the classic mistakes

Token authentication is straightforward in principle: prove the request came from someone who logged in, and let that proof be stateless. The implementation mistakes are remarkably consistent — a secret in source control, an unpinned algorithm that accepts none, a token with no expiry, and no revocation story.

python
import os
import time

import jwt
from fastapi import Depends, FastAPI, HTTPException
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials

app = FastAPI()
bearer = HTTPBearer()
SECRET = os.environ.get("JWT_SECRET", "")
ALGORITHM = "HS256"


def issue_token(user_id: str, ttl: int = 900) -> str:
    if not SECRET:
        raise RuntimeError("JWT_SECRET is not configured")
    return jwt.encode(
        {"sub": user_id, "iat": int(time.time()), "exp": int(time.time()) + ttl},
        SECRET,
        algorithm=ALGORITHM,
    )


def current_user(creds: HTTPAuthorizationCredentials = Depends(bearer)) -> str:
    try:
        payload = jwt.decode(
            creds.credentials,
            SECRET,
            algorithms=[ALGORITHM],     # pinned: never accept the token's own claim
            options={"require": ["exp", "sub"]},
        )
    except jwt.ExpiredSignatureError:
        raise HTTPException(status_code=401, detail="token expired")
    except jwt.InvalidTokenError:
        raise HTTPException(status_code=401, detail="invalid token")
    return payload["sub"]


@app.get("/me")
def me(user_id: str = Depends(current_user)):
    return {"user_id": user_id}

Pinning algorithms on decode is the defence against the algorithm-confusion attack, where a crafted header tricks the library into verifying with a public key or nothing at all. Require exp so a token cannot outlive its intent, keep the lifetime short and refresh rather than issue long-lived tokens, and remember that a signed token cannot be revoked — for logout and bans you need a server-side session version, a denylist, or a short enough expiry to bound the damage.

Rate limiting and idempotency

Limits protect the slowest shared dependency: the database, the third-party API, the one worker pool. A fixed window lets a client burst across the boundary, so a token bucket or sliding window is the usual choice, and the response must tell the client when to come back.

python
import threading
import time


class SlidingWindow:
    def __init__(self, limit: int, window: float):
        self.limit = limit
        self.window = window
        self.hits: dict[str, list[float]] = {}
        self.lock = threading.Lock()

    def allow(self, key: str) -> tuple[bool, int]:
        now = time.monotonic()
        with self.lock:
            recent = [t for t in self.hits.get(key, []) if now - t < self.window]
            if len(recent) >= self.limit:
                self.hits[key] = recent
                retry = int(self.window - (now - recent[0])) + 1
                return False, retry
            recent.append(now)
            self.hits[key] = recent
            return True, 0


limiter = SlidingWindow(limit=5, window=60)
print([limiter.allow("ip:10.0.0.1")[0] for _ in range(6)])
print(limiter.allow("ip:10.0.0.1"))

Return 429 with a Retry-After header when the window is full, and key the limiter on the authenticated user when there is one — otherwise a shared NAT address punishes an entire office. Idempotency is the other half: PUT and DELETE are naturally repeatable, but POST retries after a timeout are not, so accept an Idempotency-Key header, store the first response, and replay it for repeats of the same key.

Pagination, versioning, and caching

ConcernRecommended defaultWhy
PaginationOpaque cursor over an ordered keyOffsets scan and drift when rows are inserted
FilteringRepeated query parameters with a fixed grammarAvoids inventing a query language
VersioningURL prefix until it hurts, then a headerVisible, cacheable, easy to route
CachingETag plus Cache-Control on GETClients revalidate instead of refetching
Rate limit feedback429 + Retry-AfterRetry logic becomes deterministic

Offset pagination is fine until rows are inserted while a client pages, at which point items repeat or vanish. A cursor built from the sort key plus an opaque encoding solves it and keeps the query indexed. Version the surface only when you must: a breaking change behind the same URL is a client outage, while an unused version is pure maintenance.

CORS, timeouts, and body limits

Cross-origin rules decide which browsers may call your API at all, and they are a server-side decision: allow only the origins you operate, restrict the methods and headers you actually use, and never combine Access-Control-Allow-Origin with credentials for an arbitrary origin. A permissive CORS policy effectively removes the browser's same-origin protection from every user who visits an attacker's page.

Timeouts and payload limits belong to the same category of defence. Give upstream calls a deadline so a slow dependency cannot pin your workers, reject request bodies above a sane ceiling before parsing them, and cap the page size a client may request — an unbounded limit parameter is a denial-of-service vector with an HTTP interface. Each of these is a few lines of middleware, and together they decide whether an unusual client degrades gracefully or takes the service down.

Shipping it

An API is not finished when the endpoints work. Generate a specification from the same declarations the framework validates against, and publish it so clients can be generated rather than hand-written. Test each endpoint at the HTTP boundary with assertions on status, headers, and body shape — the contract — and keep a smoke test that runs against a deployed environment. Log one structured line per request with the route, status, latency, and correlation id, because the first question after an incident is always which endpoint was involved and how long it took.

Common Mistakes

Returning 200 with an error body for every failure

Fix: Map failures to 400, 401, 403, 404, 409, 422 or 429 so clients can branch without parsing the body

Leaving the JWT algorithm to be taken from the token header

Fix: Pin algorithms=[...] on decode, require exp, and keep the secret in the environment

Using offset pagination on a large, frequently updated collection

Fix: Use a cursor derived from the sort key so pages stay stable and the query stays indexed

Skipping rate limits until the first traffic spike

Fix: Limit at the edge or in middleware keyed by user, and return 429 with Retry-After

Best Practices

  • Design the resource model first and let routes fall out of it
  • Return one error envelope with a stable machine-readable code for every failure path
  • Keep access tokens short-lived and refresh them, with a revocation story for bans and logout
  • Support an Idempotency-Key on POST so client retries cannot double-charge
  • Generate API docs from declarations and add a smoke test against a deployed environment

Interview Questions

Q1: 401 or 403 — when do you return which?

401 means the request is unauthenticated: no credentials or invalid ones, and the client should authenticate. 403 means the caller is known but lacks permission for this resource; retrying with the same credentials will still fail.

Q2: Why is offset pagination problematic at scale?

Rows inserted or deleted between pages cause duplicates and gaps, and deep offsets force the database to scan and discard every skipped row. A cursor over the sort key keeps the lookup indexed and the pages stable.

Q3: What is the algorithm-confusion attack on JWT?

An attacker edits the token header to select a weaker algorithm, such as none or a public-key algorithm verified with a public key as an HMAC secret. Pinning the accepted algorithms on decode prevents the library from trusting the token's own claim.

Q4: How do you make POST safe to retry?

Accept a client-generated Idempotency-Key, store the first response against that key, and return the stored response for subsequent requests with the same key so a timeout retry cannot duplicate the operation.

Key Takeaways

  • Resource-shaped URLs plus a small verb table produce a predictable, greppable API surface
  • Status codes are half the contract; clients should rarely need to parse a body to decide what happened
  • One error envelope with stable codes turns logging, display, and retry logic into a single interceptor
  • JWT safety comes from pinned algorithms, required expiry, short lifetimes, and a revocation plan
  • Pagination, idempotency, and rate limits are what let the service survive real traffic and real clients
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Continue Learning

Suggested next tutorials based on this topic

Need Expert Python Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement