{}DSA Atlas

Request Design — Validation, Errors, Pagination & Versioning

Input validation layers, a consistent error model (RFC 9457 problem details), offset vs cursor vs keyset pagination with SQL, filtering/sorting/field selection, partial responses, bulk operations, long-running operations (202 + polling), file uploads, and API versioning strategies.

Intermediate6 interview questions

Validation

# FastAPI + Pydantic: schema validation at the boundary
from pydantic import BaseModel, Field, EmailStr, field_validator
from fastapi import FastAPI

class Item(BaseModel):
    product_id: str = Field(pattern=r"^prd_[A-Za-z0-9]{6,}$")
    quantity: int = Field(ge=1, le=100)

class CreateOrder(BaseModel):
    model_config = {"extra": "forbid"}          # reject unknown fields (mass-assignment defence)
    items: list[Item] = Field(min_length=1, max_length=50)
    email: EmailStr
    coupon: str | None = Field(default=None, max_length=32)

    @field_validator("coupon")
    @classmethod
    def upper(cls, v):
        return v.upper() if v else v

app = FastAPI()

@app.post("/v1/orders", status_code=201)
def create_order(body: CreateOrder):
    ...   # business-rule validation in the service layer (stock, coupon validity) → 409/422
// Express + Zod
import { z } from "zod";

const CreateOrder = z.object({
  items: z.array(z.object({
    productId: z.string().regex(/^prd_[A-Za-z0-9]{6,}$/),
    quantity: z.number().int().min(1).max(100),
  })).min(1).max(50),
  email: z.string().email(),
  coupon: z.string().max(32).optional(),
}).strict();                                   // unknown keys → error

app.post("/v1/orders", (req, res) => {
  const parsed = CreateOrder.safeParse(req.body);
  if (!parsed.success) {
    return res.status(422).type("application/problem+json").json(toProblem(parsed.error));
  }
  // ...
});
LayerValidatesError
Edge / gatewaybody size, content type, auth presence413, 415, 401
Schematypes, formats, ranges, required/unknown fields400 / 422
Domainbusiness rules, state transitions409 / 422
Databaseuniqueness, FKs, CHECKs (race-proof)map to 409

Error model: RFC 9457 Problem Details

HTTP
HTTP/1.1 422 Unprocessable Content
Content-Type: application/problem+json

{
  "type": "https://api.example.com/errors/validation",
  "title": "Your request parameters didn't validate.",
  "status": 422,
  "code": "validation_failed",
  "request_id": "req_01J9ZK7T0X",
  "errors": [
    { "field": "items[0].quantity", "code": "too_large", "message": "must be ≤ 100" },
    { "field": "email", "code": "invalid_format", "message": "is not a valid email" }
  ]
}
HTTP
HTTP/1.1 409 Conflict
Content-Type: application/problem+json

{
  "type": "https://api.example.com/errors/invalid-state",
  "title": "Order can't be cancelled",
  "status": 409,
  "code": "order_already_shipped",
  "detail": "Order ord_9Kx2 shipped at 2026-10-06T08:00:00Z.",
  "instance": "/v1/orders/ord_9Kx2:cancel"
}

Pagination

OFFSET 100000 LIMIT 20 read and throw away 100,000 rows return 20 cost grows with page depth;inserts shift pages (dupes/skips) WHERE (ts, id) < cursor LIMIT 20 index seek straight to the cursor return 20 constant cost at any depth;stable under concurrent writes keyset needs a unique, indexed sort key — add the id as a tie-breaker
Why feeds and big tables use cursor (keyset) pagination.
-- index: (created_at DESC, id DESC)
-- first page
SELECT id, created_at, title FROM post
ORDER BY created_at DESC, id DESC
LIMIT 21;                                     -- fetch one extra to know if there's a next page

-- next page: cursor = base64({"created_at": "...", "id": "..."}) of the last row returned
SELECT id, created_at, title FROM post
WHERE (created_at, id) < ($1, $2)             -- row-value comparison
ORDER BY created_at DESC, id DESC
LIMIT 21;
{
  "data": [ { "id": "pst_91", "title": "…" } ],
  "page": { "next_cursor": "eyJjcmVhdGVkX2F0IjoiMjAyNi0xMC0wN1QxMDoyMVoiLCJpZCI6InBzdF85MSJ9", "has_more": true }
}
OffsetCursor / keyset
Jump to page N✓✗
Deep-page performancedegrades linearlyconstant
Stable under inserts✗✓
Total counteasy (but costly)separate/estimated
Best forsmall admin tablesfeeds, timelines, public APIs, exports

Always cap limit (e.g. max 100) and return a default.

Filtering, sorting, field selection

Text
GET /v1/orders?status=paid&created_after=2026-10-01T00:00:00Z&min_total=1000
             &sort=-created_at,id&fields=id,status,total&expand=customer&limit=50
  • Filtering: explicit, documented params; only allow filters you can index. Complex search → a dedicated POST /orders/search with a JSON body or a search service.
  • Sorting: allow-list of sortable fields (- prefix for descending).
  • Sparse fieldsets (fields=) and expansion (expand=customer) reduce payloads and round trips.

Bulk operations

HTTP
POST /v1/contacts:batchCreate
{ "contacts": [ {...}, {...} ] }

207 Multi-Status (or 200 with per-item results)
{ "results": [ {"index":0,"status":201,"id":"con_1"}, {"index":1,"status":422,"error":{...}} ] }

Decide (and document) whether a batch is atomic (all-or-nothing in one transaction) or partial (per-item results). Limit batch sizes; for very large imports, upload a file and process asynchronously.

Long-running operations

Client API Worker POST /exports enqueue job 202 · Location: /operations/op_1 GET /operations/op_1 200 {status: running, progress: 40} done → result in S3 GET /operations/op_1 200 {status: succeeded, result_url}
Asynchronous request–reply: 202, then poll (or get a webhook/SSE notification).

File uploads

  1. POST /v1/uploads {filename, size, content_type} → API authorises, returns a pre-signed URL (or multipart part URLs).
  2. Client PUTs the bytes directly to object storage.
  3. Storage event or POST /v1/uploads/{id}:complete → worker validates and processes.
  4. Downloads via CDN with signed URLs for private files.

Versioning

StrategyExampleProsCons
Path/v1/ordersobvious, cache/route friendlyURL changes on major bumps
HeaderAPI-Version: 2026-10-01clean URLs, fine-grainedless discoverable
Media typeAccept: application/vnd.acme.v2+jsonHTTP-puristawkward tooling
Query?v=2easycaching, clutter

Interview questions

0 / 6 marked confident

Answer out loud first, then open the model answer. Mark a question confident only when you could explain it to an interviewer without notes.