12. API Design & AuthN/Z
Ship predictable, secure APIs with clear contracts, standard errors, and robust auth flows.
Question: How should a REST API handle pagination?
Answer: An API should use either offset-based pagination (limit
/offset
) or, preferably, keyset-based (cursor) pagination. Keyset pagination is more performant for large datasets as it avoids deep OFFSET
queries. The response should include metadata indicating the total number of items and links to the next/previous page.
Question: What are some common pitfalls of using JSON Web Tokens (JWTs)?
Answer: Common pitfalls include: not validating the signature algorithm (the alg: none
vulnerability), using weak secret keys, not having a key rotation strategy, and storing too much data in the payload. JWTs should also have short expiration times (exp
claim), with refresh tokens used to obtain new ones.
Question: How should an API return errors? (Problem Details RFC 7807)
Answer: Return standardized JSON with type
, title
, status
, and optional detail
/instance
to convey machine-readable errors.
Explanation: Improves client handling and observability.
from fastapi import FastAPI, HTTPException
from fastapi.responses import JSONResponse
app = FastAPI()
@app.exception_handler(HTTPException)
async def handler(_, exc: HTTPException):
return JSONResponse({
"type": "about:blank", "title": exc.detail,
"status": exc.status_code
}, status_code=exc.status_code)
Question: How do you implement conditional GETs with ETags or Last-Modified?
Answer: Include validators (ETag
, Last-Modified
) and honor If-None-Match
/If-Modified-Since
to return 304 Not Modified
when unchanged.
from fastapi import Response, Request
def get_item(req: Request) -> Response:
body, etag = compute_body_and_etag()
inm = req.headers.get("if-none-match")
if inm == etag:
return Response(status_code=304, headers={"ETag": etag})
return Response(content=body, media_type="application/json", headers={"ETag": etag})
Question: What OAuth2/OIDC flows matter for backend services?
Answer: Use Authorization Code with PKCE for web/mobile, Client Credentials for service-to-service, Refresh Tokens for long-lived sessions.
Explanation: Validate issuer, audience, expiry; rotate keys (JWKS) and use short-lived access tokens.
Question: How do you design idempotent POST endpoints?
Answer: Require an Idempotency-Key
header and store the first request’s result keyed by it; return the same response for retries.
Explanation: Prevents duplicates in network retries and client restarts.