REST API Interview Questions
Architectural questions on RESTful resource modeling, idempotency keys, HTTP status codes, OAuth 2.1 token lifetimes, rate limiting, and RFC 7231 compliance.
Practice REST API Interview Questions
Showing 16 of 16 technical questions with engineering explanations
What are the six architectural constraints of REST defined by Roy Fielding, and why does Statelessness matter most for scaling?
Senior Engineering Answer
REST defines six constraints: Client-Server separation, Statelessness, Cacheability, Layered System (proxies/CDNs/gateways), Uniform Interface (resource identification, manipulation via representations, self-descriptive messages, HATEOAS), and optional Code on Demand. Statelessness requires every request to carry all authentication and context needed to process it without relying on server-in-memory session affinity, allowing load balancers to route requests across any backend node effortlessly.
Storing user session state or shopping carts inside local server RAM (requiring sticky sessions) violates REST statelessness and causes silent session drops during auto-scaling or rolling deploys.
How do HTTP methods compare in safety and idempotency (GET, HEAD, POST, PUT, PATCH, DELETE)?
Senior Engineering Answer
A method is Safe if it never mutates server state (GET, HEAD, OPTIONS). A method is Idempotent if sending the exact same request once or multiple times leaves server state identical (GET, HEAD, PUT, DELETE). PUT replaces the entire target resource cleanly, making repeats identical. POST creates new resources or triggers non-idempotent actions, so blind retries risk duplicate records. PATCH applies partial updates and may or may not be idempotent depending on payload semantics (e.g., setting a field vs incrementing a counter).
PUT /v1/users/42 # Idempotent full replacement
PATCH /v1/users/42 # Partial update (e.g. {"email": "new@example.com"})
POST /v1/orders # Non-idempotent creation unless keyed by Idempotency-KeyUsing HTTP GET endpoints to trigger state mutations (like /logout or /approve?id=9) breaks browser prefetching, crawlers, and HTTP caching semantics.
When should a REST API return 400 vs 401 vs 403 vs 404 vs 409 vs 422 vs 429 vs 503?
Senior Engineering Answer
400 Bad Request indicates malformed syntax or invalid JSON framing. 401 Unauthorized means missing or invalid authentication credentials (who you are), whereas 403 Forbidden means credentials are valid but lack permission (what you may access). 404 Not Found indicates an absent resource (also used intentionally instead of 403 to hide resource existence). 409 Conflict signals state collisions like duplicate unique keys or stale version writes; 422 Unprocessable Content means valid JSON that fails semantic/business validation; 429 indicates rate limiting (with Retry-After); and 503 signals temporary server/dependency unavailability.
HTTP/1.1 422 Unprocessable Content
Content-Type: application/problem+json
{
"type": "https://api.example.com/errors/validation",
"title": "Validation Failed",
"status": 422,
"errors": [{ "field": "shipDate", "message": "Must be in the future" }]
}Returning 200 OK with {"success": false, "error": ...} breaks standard HTTP monitoring, client retry libraries, CDN negative caching, and API gateways.
How should REST resource URIs, filtering, sorting, and standardized errors (RFC 9457 Problem Details) be structured?
Senior Engineering Answer
REST URIs identify nouns/collections in plural lowercase kebab-case (/v1/organizations/{orgId}/invoices) rather than RPC verbs (/getInvoicesForOrg), using HTTP methods to express actions. Filtering, sorting, and field selection belong in query parameters (?status=paid&sort=-createdAt). Standardized errors should follow RFC 9457 (formerly RFC 7807) Problem Details (application/problem+json) with type, title, status, detail, and instance fields so clients handle errors uniformly across endpoints.
GET /v1/invoices?status=overdue&sort=-dueDate&limit=25 DELETE /v1/organizations/acme/members/usr_91
Leaking internal database stack traces, SQL errors, or raw framework exceptions inside 500 error bodies exposes schema and security details to attackers.
How do Offset/Limit pagination and Cursor (Keyset) pagination differ in consistency and database performance?
Senior Engineering Answer
Offset/Limit (?offset=10000&limit=50) allows jumping to arbitrary page numbers, but degrades to O(offset + limit) as databases scan and discard skipped rows, and causes missed or duplicated items whenever new rows are inserted or deleted concurrently. Cursor (Keyset) pagination encodes an opaque tie-broken bookmark (such as base64(createdAt + id)) and queries WHERE (created_at, id) < (?, ?) LIMIT 50, yielding consistent O(log N) B-tree index performance at any depth without drift.
GET /v1/events?limit=50&cursor=eyJ0cyI6MTc2MjkwMDAwMCwiaWQiOiJldl85ODQifQ -- Backing SQL keyset query: SELECT * FROM events WHERE (created_at, id) < ($1, $2) ORDER BY created_at DESC, id DESC LIMIT 50;
Using only a non-unique timestamp as a cursor drops events when multiple records share the exact same millisecond; always include a unique tie-breaker column like id.
How do HTTP ETag, If-None-Match, and If-Match headers implement both response caching and optimistic concurrency control?
Senior Engineering Answer
An ETag is an opaque version identifier (hash or revision number) returned on GET/PUT responses. For conditional caching, clients include If-None-Match: "v42"; if unchanged, the server returns 304 Not Modified with an empty body, saving bandwidth and serialization. For optimistic concurrency control (preventing lost updates), clients send If-Match: "v42" on PUT/PATCH/DELETE; if another writer already bumped the resource to "v43", the server rejects the stale write with 412 Precondition Failed.
PATCH /v1/orders/ord_77 HTTP/1.1
If-Match: "rev-14"
Content-Type: application/json
{ "shippingTier": "express" }Returning weak ETags (W/"...") on endpoints meant for byte-exact If-Match updates fails strict strong comparison checks in RFC 9110, rejecting valid concurrency updates.
How do Cache-Control directives (public, private, max-age, s-maxage, stale-while-revalidate, Vary) control browser vs CDN caching?
Senior Engineering Answer
Cache-Control: private restricts caching solely to the user's browser (essential for personalized responses), whereas public allows shared CDNs/proxies to cache. max-age sets browser TTL while s-maxage overrides TTL specifically for shared CDN caches. stale-while-revalidate lets CDNs serve slightly expired content instantly while refreshing asynchronously in the background. The Vary header (e.g., Vary: Accept-Encoding, Accept-Language) prevents CDNs from serving a gzipped or Spanish response to a client requesting raw English.
Cache-Control: public, max-age=60, s-maxage=3600, stale-while-revalidate=300 Vary: Accept-Encoding, Accept
Caching authenticated or user-specific endpoints without Cache-Control: private or no-store can leak one user's sensitive payload to another user through a shared CDN or corporate proxy.
What are the trade-offs between URI path versioning, Header/Accept versioning, and additive backward-compatible evolution?
Senior Engineering Answer
URI versioning (/v1/orders) is explicit, browser-testable, and trivially routable at API gateways/CDNs, though it fractures resource URLs across versions. Header versioning (Accept: application/vnd.api.v2+json) keeps resource URIs pure and REST-compliant, but complicates curl debugging and requires Vary: Accept caching rules. Most high-velocity API teams combine coarse major URI versions (/v1) with strict additive backward compatibility (never renaming, removing, or tightening required fields within a version).
GET /v1/customers/cus_12 HTTP/1.1 Accept: application/json
Bumping an entire API to /v2 for minor breaking changes forces duplicating routing, auth, and test suites across versions—use expand-and-contract migrations and Deprecation/Sunset headers instead.
How do you implement Idempotency-Key support for POST payment and order endpoints to survive client retries and race conditions?
Senior Engineering Answer
Because network timeouts leave clients unsure whether a POST succeeded, clients attach a unique UUID in Idempotency-Key. The server stores the key atomically (e.g., database unique constraint or Redis SET NX) along with a hash of the request payload and processing state. If an identical retry arrives concurrently while in-flight, return 409 Conflict (or wait briefly); if completed, replay the exact saved HTTP status code and JSON body; if the same key is reused with a different payload hash, reject with 422/400.
POST /v1/charges HTTP/1.1
Idempotency-Key: 9f4d7b2a-8c1e-4b65-a23d-1188a0c7f901
Content-Type: application/json
{ "amountCents": 4900, "currency": "USD" }Checking Redis for an existing Idempotency-Key and inserting it non-atomically without a lock or unique DB constraint creates a TOCTOU race condition where two parallel retries both charge the customer.
How do Token Bucket, Sliding Window Counter, and Distributed Redis rate limiters work, and what standard headers should APIs return?
Senior Engineering Answer
Token Bucket refills tokens at a fixed rate up to a burst capacity; each request consumes a token and allows controlled bursts while capping average throughput. Sliding Window Counter blends weighted counts from the previous and current fixed windows to eliminate boundary double-burst spikes with O(1) memory per key. In distributed APIs, execute rate checks inside atomic Redis Lua scripts to avoid race conditions, returning 429 Too Many Requests with Retry-After and RateLimit-Limit/Remaining/Reset headers.
-- Atomic Redis Lua token-bucket check (KEYS[1] = bucket key)
local tokens = tonumber(redis.call('HGET', KEYS[1], 'tokens') or ARGV[1])
local last = tonumber(redis.call('HGET', KEYS[1], 'ts') or ARGV[2])
-- Refill elapsed tokens, decrement 1 if >= 1, else return 0 (429)Using naive Fixed Window counters lets a client send 100% of their minute quota at 00:59 and another 100% at 01:01, delivering 2x intended peak load within two seconds.
How does HATEOAS work in practice, and when is hypermedia worth its payload overhead versus OpenAPI schemas?
Senior Engineering Answer
HATEOAS embeds state-driven hypermedia links (_links / actions) inside responses so clients discover valid next transitions dynamically based on server workflow state (e.g., showing 'refund' and 'track' only after an order transitions to 'paid', omitting 'cancel' once 'shipped'). It excels in complex workflow engines, payment state machines, and BFFs where business rules govern UI actions—whereas strongly typed internal microservices often prefer static OpenAPI 3.1 contracts to avoid link-crawling boilerplate.
{
"id": "ord_881",
"status": "paid",
"total": 120.00,
"_links": {
"self": { "href": "/v1/orders/ord_881" },
"refund": { "href": "/v1/orders/ord_881/refunds", "method": "POST" }
}
}Duplicating authorization/state-machine logic in both frontend clients and backend servers causes drift; returning server-computed capability links keeps workflow rules single-sourced.
How do you handle long-running operations asynchronously in a REST API using 202 Accepted, Location polling, and Webhooks?
Senior Engineering Answer
Blocking an HTTP connection for >30 seconds exhausts server workers and trips load-balancer timeouts. Instead, accept the command quickly, persist a job record, enqueue background work, and immediately return 202 Accepted with a Location (or Content-Location) header pointing to /v1/jobs/{jobId} plus Retry-After. Clients poll that status endpoint (which transitions to 200 OK with the result or 303 See Other pointing to the created resource) or register HMAC-signed webhooks with exponential backoff retries.
HTTP/1.1 202 Accepted
Location: /v1/exports/exp_409
Retry-After: 5
{ "id": "exp_409", "status": "queued" }Sending unsigned webhooks allows attackers to spoof event callbacks; always sign webhook payloads with HMAC-SHA256 + timestamp replay windows and verify signatures in constant time.
How do you protect REST APIs against OWASP API Security Top 10 risks (BOLA/IDOR, Mass Assignment, SSRF, and JWT pitfalls)?
Senior Engineering Answer
Broken Object Level Authorization (BOLA/IDOR) occurs when an endpoint checks that a user is logged in but fails to verify ownership of /orders/{id}—every repository query must scope by authenticated tenant/owner ID. Prevent Mass Assignment by strictly allowlisting incoming DTO fields instead of binding raw JSON directly to ORM models. Mitigate SSRF on URL-fetching endpoints by blocking private/link-local CIDRs (169.254.169.254, 10.0.0.0/8) after DNS resolution. Always pin expected JWT algorithms server-side (rejecting alg=none and HS256/RS256 confusion) and validate iss, aud, and exp.
// Enforce tenant/owner scope directly in data access layer SELECT * FROM invoices WHERE id = $1 AND organization_id = $2;
Checking ownership only in a route middleware using URL parameters without scoping database queries leaves nested/batch endpoints vulnerable to BOLA when arrays of IDs are passed in the body.
How do BFFs (Backends for Frontends), API Gateways, and request coalescing solve N+1 chatty REST round-trips and thundering herds?
Senior Engineering Answer
Fine-grained domain REST services force mobile or web clients into waterfall N+1 requests. A BFF aggregates and reshapes multiple downstream calls concurrently on low-latency internal networks tailored to each client surface (mobile vs web), while an API Gateway centralizes TLS termination, JWT verification, rate limiting, and routing. For hot cache expirations that trigger thundering herds, apply singleflight request coalescing so N concurrent requests for the same key await one backend fetch.
// Singleflight coalescing prevents duplicate origin fetches on cache miss
val, err, _ := group.Do(cacheKey, func() (any, error) {
return fetchAndCacheResource(ctx, cacheKey)
})Putting domain business logic or cross-service transaction orchestration inside an API Gateway turns the gateway into a brittle, untestable monolith bottleneck.
How do HTTP/2 multiplexing, HTTP/3 (QUIC), TLS session resumption, and gRPC compare to JSON-over-HTTP/1.1 REST APIs?
Senior Engineering Answer
HTTP/1.1 suffers from head-of-line blocking and forces browsers to open ~6 parallel TCP connections per origin. HTTP/2 multiplexes concurrent streams over a single TCP connection with HPACK header compression, though TCP packet loss still stalls all streams (TCP head-of-line blocking). HTTP/3 runs over QUIC (UDP), giving independent per-stream recovery and 0-RTT connection resumption across mobile IP switches. While public APIs favor REST/JSON for universal tooling and HTTP cacheability, internal low-latency RPCs often choose gRPC (HTTP/2 + binary Protobuf contracts) for 5x-10x smaller payloads and strict streaming.
Blindly enabling gRPC for public browser-facing APIs without gRPC-Web/Connect proxies breaks standard HTTP/CDN caching, curl debugging, and broad third-party webhook integrations.
How do you design graceful degradation, load shedding, adaptive concurrency limits, and circuit breakers in high-scale REST services?
Senior Engineering Answer
When a downstream dependency slows down, unbounded retries and static timeouts trigger cascading retry storms and thread-pool exhaustion. Resilient REST APIs propagate strict per-request deadline budgets (dropping work once elapsed time exceeds remaining budget), enforce client retries only with exponential backoff plus full jitter, trip Circuit Breakers quickly on elevated error/latency rates to fail fast or serve stale cached fallbacks, and shed excess load at ingress using adaptive concurrency limits (e.g., Little's Law / Vegas/Gradient algorithms) with 503 + Retry-After before queues explode.
// Exponential backoff with full jitter avoids synchronized retry waves const backoffMs = Math.random() * Math.min(maxDelayMs, baseDelayMs * Math.pow(2, attempt));
Adding client retries at multiple layers (SDK + Envoy sidecar + API Gateway) multiplies a single outage by 3^3 = 27x traffic amplification, turning a brief blip into a total collapse.
REST API Track Coverage & Difficulty Profile
14 of 16 prompts include code examplesThis REST API preparation set groups 16 prompts across Junior (4), Mid-Level (4), Senior (4), Principal / Staff (4) roles with 4 fundamental, 4 intermediate, 4 advanced, 4 staff exercises tailored to Frontend & Core Web.
What are the six architectural constraints of REST defined by Roy Fielding, and why does Statelessness matter most for scaling?
How do HTTP methods compare in safety and idempotency (GET, HEAD, POST, PUT, PATCH, DELETE)?
When should a REST API return 400 vs 401 vs 403 vs 404 vs 409 vs 422 vs 429 vs 503?
How should REST resource URIs, filtering, sorting, and standardized errors (RFC 9457 Problem Details) be structured?
How do Offset/Limit pagination and Cursor (Keyset) pagination differ in consistency and database performance?
How do HTTP ETag, If-None-Match, and If-Match headers implement both response caching and optimistic concurrency control?
Frequently Asked Technical Interview Questions (REST API)
Essential theoretical concepts, architecture trade-offs, and runtime design questions asked by hiring committees.
What is the difference between PUT and PATCH in REST APIs?
Why should REST APIs avoid passing sensitive tokens or PII inside URL query parameters?
How do CORS preflight OPTIONS requests work for cross-origin REST APIs?
When should an API return 204 No Content versus 200 OK?
Pair Interview Prep with Cheat Sheets & Roadmaps
Review syntax formulas on our interactive cheat sheets, test your skills in technical quizzes, and study high-scale system designs.
Want to practice other technologies?
Explore our comprehensive technical interview tracks across all core technology stacks.