83 REST API Interview Questions and Answers (2026)

Blog / 83 REST API Interview Questions and Answers (2026)
REST API interview questions and answers

REST API is now the default for shipping Python APIs and AI/ML backends, which means more companies build on it and more interviewers expect real fluency. That bar keeps rising. Walk in shaky on statelessness, status codes, or versioning and a stronger candidate takes the offer.

This is 83 questions with tight, interview-ready answers and code where it helps. They're worked Junior to Mid to Senior, so you start with fundamentals and build to the deep design and security stuff. Work through them and you'll have an answer ready for whatever they throw at you.

Q1.
What does "Statelessness" actually mean in a RESTful context?

Junior

Statelessness means each request from the client must contain all the information needed to process it: the server keeps no client session state between requests. Any necessary state lives either on the client or in a shared datastore, never in the server's memory tied to a specific connection.

  • Each request is self-contained: Credentials, context, and parameters travel with every call (e.g. a token in the Authorization header).

  • No server-side session affinity: The server doesn't remember "who you are" from a previous request; nothing is stored between calls.

  • Application vs. resource state: Application/session state belongs to the client; resource state (the actual data) still lives on the server, in a database.

  • Trade-off: More data is sent per request, but you gain visibility, reliability, and scalability.

Q2.
What is a "Resource" in REST?

Junior

A resource is any named piece of information the API exposes: the key abstraction in REST, identified by a URI, that the server represents to the client.

  • It is a concept, not a file: A user, an order, a search result, or even a relationship; anything worth referencing.

  • Identified by a URI: Each resource has a stable identifier (e.g. /users/7) clients use to address it.

  • Accessed via representations:

    • Clients never touch the resource directly; they exchange representations of its state (JSON, XML, etc.).

    • The same resource can have multiple representations negotiated via Accept.

  • Manipulated with uniform methods: HTTP verbs (GET, PUT, DELETE) act on the resource the URI names.

Q3.
What is the difference between a "Collection" resource and an "Instance" resource?

Junior

A collection resource represents a group of items (e.g. all users), while an instance resource represents a single member of that group (e.g. one specific user).

  • Collection resource:

    • URI is typically a plural noun: /users.

    • GET lists/filters members; POST creates a new member (server assigns its ID).

  • Instance resource:

    • URI adds an identifier: /users/7.

    • GET reads it; PUT/PATCH updates it; DELETE removes it.

  • Method semantics differ by type: POST to a collection creates; PUT to an instance replaces. Don't POST to an instance to create children unless that instance is itself a sub-collection (/users/7/orders).

Q4.
Why is POST considered neither safe nor idempotent?

Junior

POST is unsafe because it changes server state, and non-idempotent because each call typically produces a new, distinct effect (a new resource or another action). Sending it twice usually creates two outcomes, not one.

  • Not safe: It mutates state: creating records, submitting orders, triggering processes.

  • Not idempotent:

    • POST /orders called twice creates two orders with two different IDs.

    • The server, not the client, usually assigns the resource location, so there's no fixed target to overwrite.

  • Consequences:

    • Intermediaries must not automatically retry or cache POST by default.

    • To make retries safe, add an idempotency key so duplicates collapse into one effect.

Q5.
Explain the difference between POST and PUT when creating a resource.

Junior

Both can create a resource, but POST lets the server assign the URI and is non-idempotent, while PUT creates (or replaces) a resource at a client-specified URI and is idempotent.

  • POST to a collection:

    • POST /users: the server generates the ID and returns it (often with 201 Created and a Location header).

    • Calling it twice makes two resources, so it is not idempotent.

  • PUT to a specific URI:

    • PUT /users/42: the client chooses the identifier; the server creates it if absent or replaces it if present.

    • Calling it twice with the same body leaves the same single resource, so it is idempotent.

  • Rule of thumb: use POST when the server owns ID generation, PUT when the client knows the target URI.

Q6.
What is the difference between a 401 Unauthorized and a 403 Forbidden status code?

Junior

401 means "I don't know who you are" (authentication failed or is missing); 403 means "I know who you are, but you're not allowed to do this" (authorization failed).

  • 401 Unauthorized = authentication problem:

    • No credentials, invalid token, or expired session.

    • Should include a WWW-Authenticate header telling the client how to authenticate.

    • Fix: log in / provide valid credentials.

  • 403 Forbidden = authorization problem:

    • Credentials are valid but lack the permission/role for this resource.

    • Re-authenticating won't help: the identity simply isn't allowed.

  • Privacy nuance: Sometimes a 404 is returned instead of 403 to avoid revealing that a resource exists to unauthorized users.

Q7.
How do you handle a request for a resource that has been permanently moved to a new URL?

Junior

Return 301 Moved Permanently with a Location header pointing to the new URL, telling clients and caches to use the new address from now on.

  • 301 Moved Permanently:

    • Signals the move is permanent; clients should update bookmarks/links and caches may store it indefinitely.

    • Include the new address in the Location header.

  • Watch the method-change pitfall: Historically clients may rewrite a POST to GET on 301; use 308 Permanent Redirect to preserve the original method and body.

  • Permanent vs temporary: For a temporary move use 302 / 307 so clients keep using the original URL.

  • Gone vs moved: If the resource is removed with no replacement, use 410 Gone instead.

Q8.
What are the main categories of HTTP status codes (2xx, 3xx, 4xx, 5xx), and what does each class signify?

Junior

HTTP status codes are grouped by their first digit into five classes, each signaling the broad outcome of a request so clients can react without parsing the body.

  • 1xx Informational: Provisional, interim responses (e.g. 100 Continue); rarely surfaced in app code.

  • 2xx Success: Request received and processed: 200 OK, 201 Created, 204 No Content.

  • 3xx Redirection: Further action needed, usually following a new location: 301 Moved Permanently, 304 Not Modified.

  • 4xx Client Error: The client's request is at fault: 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found. Don't retry unchanged.

  • 5xx Server Error: The server failed to fulfill a valid request: 500 Internal Server Error, 503 Service Unavailable. Often safe to retry.

Q9.
What is the best practice for naming RESTful endpoints? Explain the use of nouns vs. verbs.

Junior

Name endpoints with plural nouns that represent resources, not verbs that represent actions: the HTTP method already supplies the verb, so the URI only needs to identify the thing being acted on.

  • Nouns, not verbs:

    • Use /users, not /getUsers or /createUser.

    • The method conveys intent: GET /users, POST /users, DELETE /users/42.

  • Prefer plural, consistent collections: Collection: /orders; single item: /orders/{id}.

  • Lowercase and hyphenated: Use /purchase-orders, not /purchaseOrders or /PurchaseOrders; avoid trailing slashes.

  • Why it matters: A noun-based, uniform interface is predictable and lets clients guess endpoints; verb names cause an explosion of inconsistent routes.

Q10.
What is the difference between a Path Parameter and a Query Parameter, and when would you use each?

Junior

A path parameter identifies a specific resource and is part of the URL path; a query parameter refines or modifies how a collection is returned and comes after the ?. Use path params for identity, query params for options.

  • Path parameter: identifies a resource:

    • Hierarchical and required (e.g. /users/42 where 42 is the user id).

    • Each value points to a single, distinct entity; changing it changes which resource you address.

  • Query parameter: modifies a request:

    • Optional, often with defaults (e.g. /users?status=active&page=2).

    • Used for filtering, sorting, pagination, and search over a collection.

  • Rule of thumb: If removing it makes the URL meaningless, it's a path param; if it just narrows results, it's a query param.

Q11.
What is the difference between authentication and authorization in the context of an API?

Junior

Authentication verifies who you are; authorization decides what you're allowed to do. Authentication always comes first, then authorization governs access to specific resources or actions.

  • Authentication (AuthN):

    • Confirms identity via credentials: passwords, API keys, tokens, certificates.

    • Failure returns 401 Unauthorized (you are not identified).

  • Authorization (AuthZ):

    • Confirms permissions: roles, scopes, ownership, policies (RBAC/ABAC).

    • Failure returns 403 Forbidden (identified, but not permitted).

  • Order and relationship:

    • You authenticate once, then every request is authorized against what that identity can access.

    • A valid token (authenticated) can still be denied a resource (not authorized).

Q12.
Why is HTTPS/TLS considered a requirement for REST APIs rather than an optional feature?

Junior

HTTPS/TLS encrypts the connection between client and server, so without it every request, including credentials and tokens, travels as plaintext that anyone on the network path can read or tamper with. For an API that carries auth and data, that's an unacceptable default, which is why it's treated as a requirement, not an option.

  • Confidentiality: Encrypts payloads, headers, and tokens so passwords, API keys, and Authorization bearer tokens can't be sniffed.

  • Integrity: Prevents man-in-the-middle tampering: an attacker can't silently modify requests or responses in transit.

  • Authenticity: The server's certificate proves clients are talking to the real host, not an impostor.

  • It underpins other security: Token-based auth, cookies, and OAuth flows assume a private channel; over plaintext they're trivially stolen and replayed.

  • Practical expectations:

    • Redirect HTTP to HTTPS and send HSTS so browsers refuse plaintext.

    • Increasingly mandatory: modern browsers and features (HTTP/2, service workers) require it anyway.

Q13.
Explain the Richardson Maturity Model. At what level does an API become truly RESTful?

Mid

The Richardson Maturity Model grades an API's adherence to REST in four levels (0 to 3), measuring how well it uses resources, HTTP verbs, and hypermedia. Most agree an API becomes truly RESTful only at Level 3, where hypermedia (HATEOAS) is present, though many in practice consider Level 2 "RESTful enough."

  • Level 0: The Swamp of POX: A single endpoint, usually one HTTP verb (often POST), used as an RPC tunnel (e.g. SOAP).

  • Level 1: Resources: Many URIs identify individual resources (/users/1), but verbs are still misused.

  • Level 2: HTTP Verbs: Proper use of methods (GET, POST, PUT, DELETE) and status codes. Most real-world "REST" APIs sit here.

  • Level 3: Hypermedia Controls (HATEOAS): Responses include links telling the client what it can do next, making the API self-descriptive and discoverable.

  • The verdict: By Roy Fielding's definition, only Level 3 is fully RESTful, but Level 2 is the pragmatic industry baseline.

Q14.
What are the six architectural constraints of REST, and why do they matter?

Mid

REST defines six constraints (five mandatory plus one optional) that, taken together, produce the scalability, simplicity, and evolvability of the web. An API that violates the required constraints isn't truly RESTful.

  • Client-Server: Separate UI/client concerns from data/server concerns so each evolves independently.

  • Stateless: Each request carries all context it needs; the server stores no client session state. Enables easy scaling.

  • Cacheable: Responses declare whether they are cacheable (e.g. Cache-Control), reducing load and latency.

  • Uniform Interface: A standardized way to interact with resources (URIs, verbs, representations). The defining feature of REST.

  • Layered System: Clients can't tell if they talk to the origin server or an intermediary (proxy, gateway, load balancer).

  • Code on Demand (optional): Servers may send executable code (e.g. JavaScript) to extend the client. The only optional constraint.

Q15.
What is HATEOAS, and what problem is it trying to solve in RESTful design?

Mid

HATEOAS (Hypermedia As The Engine Of Application State) means a response includes links describing the actions a client can take next, so the client navigates the API by following links rather than hardcoding URLs. It's the constraint that makes an API self-descriptive and decoupled from its URI structure.

  • The problem it solves:

    • Tight coupling: without it, clients hardcode URI templates and break when the server changes them.

    • Discoverability: the server can guide the client through valid state transitions dynamically.

  • How it works:

    • Each representation carries links (relations like self, next, cancel) indicating what is currently possible.

    • State drives the links: a paid order won't show a pay link, only a refund link.

  • Significance: It is the requirement for Richardson Level 3 and the core of Fielding's original REST vision.

json

{ "id": 42, "status": "pending", "_links": { "self": { "href": "/orders/42" }, "pay": { "href": "/orders/42/pay" }, "cancel": { "href": "/orders/42/cancel" } } }

Q16.
What makes an API "RESTful" versus just being an HTTP-based API?

Mid

Any API over HTTP uses the protocol as transport; a RESTful API additionally honors REST's architectural constraints, treating HTTP as the application semantics (resources, verbs, status codes, caching). The difference is using HTTP correctly versus just using it as a pipe.

  • Resource-oriented, not action-oriented: URLs name nouns (/users/1), not verbs (/getUser?id=1).

  • Verbs carry meaning: Uses GET/POST/PUT/DELETE per their semantics, respecting safety and idempotency.

  • Proper status codes: Returns 201, 404, 409 instead of always 200 with an error embedded in the body.

  • Obeys the constraints: Stateless, cacheable, uniform interface, layered. An HTTP-RPC service ignores these.

  • Bottom line: "HTTP API" describes the transport; "RESTful" describes the design discipline applied on top of it.

Q17.
Explain the concept of "Statelessness" in REST and why is it important for horizontal scaling?

Mid

Statelessness means the server stores no client session state, so every request stands alone with all the context it needs. This is precisely what makes horizontal scaling easy: any server instance can handle any request, because none of them holds session memory the others lack.

  • What statelessness requires: Each request carries auth and context (e.g. a JWT), so processing never depends on prior requests.

  • Why it enables horizontal scaling:

    • Any node can serve any request: a load balancer can route freely with no "sticky sessions."

    • Adding or removing instances is trivial; no session replication between servers is needed.

    • Failover is seamless: if a node dies, another handles the next request without losing session data.

  • Where shared state goes: If you genuinely need cross-request state, push it to a shared store (e.g. Redis) or a database, not server memory.

  • Cost: Larger requests and repeated auth work, traded for elastic, resilient scaling.

Q18.
What are conditional requests, and how do Last-Modified and If-Modified-Since headers work together?

Mid

Conditional requests let a client act only if a resource has (or hasn't) changed, saving bandwidth and avoiding lost updates. Last-Modified and If-Modified-Since pair up to do time-based cache validation.

  • Server sends Last-Modified: In the response, it's a timestamp of when the resource last changed.

  • Client echoes If-Modified-Since: On the next GET, the client sends back that timestamp asking "only send the body if it changed since this."

  • Server compares and responds:

    • Unchanged: 304 Not Modified with no body (client reuses its cache).

    • Changed: 200 OK with the new body and a fresh Last-Modified.

  • ETag is the stronger sibling: ETag/If-None-Match use a content hash instead of a timestamp, which is more precise (sub-second changes) and supports If-Match for optimistic concurrency on writes.

Q19.
What is the 'cacheability' constraint in REST, and how does it influence API design?

Mid

Cacheability requires that responses explicitly declare whether they can be cached, so clients and intermediaries can reuse them instead of repeating requests, improving scalability and latency.

  • Responses must label their cacheability: Use Cache-Control (max-age, no-store, private, public) to state if and how long a response is reusable.

  • Validators enable revalidation: ETag and Last-Modified let a cache check freshness cheaply with a 304.

  • Design influence:

    • Favor GET for readable, cacheable data; keep it safe and idempotent.

    • Mark user-specific or sensitive data private or no-store.

    • Stable, predictable URIs make caching effective.

  • Benefits: Fewer round trips, lower server load, better perceived performance, and CDN/proxy reuse.

Q20.
What does the 'layered system' constraint mean in REST, and what are its benefits?

Mid

The layered system constraint says the architecture can be composed of hierarchical layers (proxies, gateways, caches, load balancers) where each component only knows the layer it talks to, not the whole chain.

  • Components can't see beyond their neighbor: A client can't tell whether it's connected to the origin server or an intermediary.

  • Intermediaries are transparent: Load balancers, caches, and gateways can sit in between without clients or servers needing changes.

  • Benefits:

    1. Scalability: add caching and load-balancing layers freely.

    2. Security: enforce policy and shield internal systems at a boundary layer.

    3. Evolvability: refactor backends behind a stable interface.

  • Trade-off: Extra layers can add latency, often offset by shared caching.

Q21.
What is the difference between "Safe" and "Idempotent" methods, and which HTTP methods fall into which category?

Mid

Safe means the method has no observable side effects on the server (read-only); idempotent means making the same request many times has the same effect as making it once. Safe implies idempotent, but not vice versa.

  • Safe methods:

    • Don't modify server state, so caches and crawlers can call them freely.

    • Includes GET, HEAD, and OPTIONS.

  • Idempotent methods:

    • Repeating the call yields the same end state (the response code may differ).

    • Includes all safe methods plus PUT and DELETE.

    • Example: DELETE /users/5 twice still leaves the user deleted (second call may return 404).

  • Neither safe nor idempotent: POST and typically PATCH: repeating can create duplicates or compound changes.

  • Why it matters: clients, proxies, and gateways can safely retry safe/idempotent requests after a network failure.

Q22.
When should you use PUT versus PATCH, and what is the conceptual difference between a full replacement and a partial update?

Mid

Use PUT to replace a resource entirely with the payload you send, and PATCH to apply a partial modification to specific fields. The core difference is full replacement versus targeted update.

  • PUT is a full replacement:

    • The body represents the complete resource; omitted fields are typically cleared or reset to defaults.

    • Idempotent: sending the same representation repeatedly produces the same state.

  • PATCH is a partial update:

    • The body describes only the changes (e.g. one field), leaving the rest untouched.

    • Not guaranteed idempotent: a patch like "increment count" changes state on each call.

  • Practical guidance: Use PUT when the client holds and submits the whole resource; use PATCH for small edits to large resources to save bandwidth.

Q23.
Why would you use the OPTIONS method and how does it relate to CORS preflight requests?

Mid

OPTIONS asks the server which methods and capabilities are allowed for a resource. Browsers use it automatically as a CORS preflight: before certain cross-origin requests, they send an OPTIONS probe to check permission.

  • General purpose: It's safe and idempotent; the server replies with an Allow header listing supported methods.

  • CORS preflight:

    • Triggered for "non-simple" requests (custom headers, methods like PUT/DELETE, certain content types).

    • The browser sends OPTIONS with Access-Control-Request-Method and Access-Control-Request-Headers.

    • The server responds with Access-Control-Allow-Origin, -Allow-Methods, and -Allow-Headers; only if it approves does the real request go out.

  • Practical note: preflight responses can be cached via Access-Control-Max-Age to avoid repeating the probe.

Q24.
Explain the concept of 'idempotency.' Which HTTP methods are idempotent, and why does it matter for a distributed system?

Mid

Idempotency means that performing the same operation multiple times leaves the system in the same final state as performing it once. It matters because networks are unreliable, and idempotent operations can be safely retried.

  • Which methods are idempotent:

    • GET, HEAD, OPTIONS (also safe), plus PUT and DELETE.

    • Not idempotent: POST and generally PATCH.

  • Why it matters in distributed systems:

    • A response can be lost even when the server succeeded, leaving the client unsure.

    • For idempotent methods, the client (or a proxy) can retry safely without corrupting state.

    • For non-idempotent ones, retries need extra protection like an idempotency key.

  • Note: idempotency is about the resulting state, not identical response bodies (a repeated DELETE may return 404 the second time).

Q25.
When would you use a POST instead of a GET for a 'read' operation?

Mid

Use POST for a read when the query itself is too large or sensitive to fit safely in a URL, accepting that you lose the semantics and caching benefits of GET.

  • Common reasons:

    • Large or complex query payloads (nested filters, geometries) that exceed URL length limits.

    • Sensitive parameters you don't want logged in URLs, proxies, or browser history.

    • Search endpoints that need a structured JSON body to express the criteria.

  • Trade-offs you accept:

    • Loss of HTTP caching and the semantic clarity that the call is read-only.

    • It is no longer safe/idempotent by convention, even though it doesn't change state.

  • Mitigations:

    • Use a clear path like POST /search to signal intent.

    • Some APIs offer QUERY or a GET-with-body alternative, but support is limited.

Q26.
Why is DELETE considered idempotent even if the second call returns a 404 Not Found?

Mid

Idempotency is about the resulting state of the server, not the response code: deleting a resource leaves the server in the same end state no matter how many times you call DELETE.

  • Idempotent = same effect on server state: After the first DELETE the resource is gone; subsequent calls don't change anything further.

  • The status code can differ:

    • First call returns 200 or 204; the second returns 404 because the resource no longer exists.

    • Idempotency makes no promise about identical responses, only identical server state.

  • Why this matters in practice: A client that retries a DELETE after a network timeout won't corrupt anything: the resource ends up deleted regardless.

Q27.
What is the purpose of the HEAD method and when is it more efficient than a GET request?

Mid

HEAD works exactly like GET but returns only the response headers with no body, letting a client inspect metadata about a resource without transferring its content.

  • Same semantics as GET, minus the body: Returns identical headers (Content-Length, Content-Type, ETag, Last-Modified) the GET would.

  • When it's more efficient:

    • Checking existence: a quick 200 vs 404 without downloading the payload.

    • Cache validation: compare ETag or Last-Modified before deciding to refetch.

    • Checking size before download: read Content-Length for a large file.

  • It's safe and idempotent: No side effects, so it's freely retryable and cacheable.

Q28.
When would you return a 202 Accepted instead of a 201 Created or 200 OK?

Mid

Return 202 Accepted when the request is valid and accepted for processing but the work happens asynchronously, so the result isn't ready (and the resource isn't yet created) when you respond.

  • 202 Accepted: deferred/async processing:

    • Used for queued jobs, batch processing, or workflows that complete later.

    • Typically returns a status/polling URL (e.g. in Location) so the client can track progress.

  • Contrast with 201 Created: 201 means the resource now exists synchronously, usually with its Location header.

  • Contrast with 200 OK: 200 means the request fully completed and the response body holds the result.

  • Key caveat: 202 makes no commitment that processing will succeed: it only acknowledges acceptance.

Q29.
What is RFC 7807 (Problem Details for HTTP APIs) and why is a standardized error response format important for API consumers?

Mid

RFC 7807 defines Problem Details, a standard JSON (or XML) format for HTTP error responses, using the media type application/problem+json so clients can parse errors consistently across APIs.

  • Standard fields:

    • type (URI identifying the error), title (short summary), status (HTTP code), detail (human-readable explanation), instance (URI of this occurrence).

    • You can add custom extension members (e.g. a errors array for field validation).

  • Why standardization matters:

    • Consumers write one error-handling path instead of guessing each API's bespoke shape.

    • Machine-readable type URIs let clients branch on error categories reliably.

    • Carries both human and machine context, aiding debugging and tooling.

json

{ "type": "https://api.example.com/errors/insufficient-funds", "title": "Insufficient funds", "status": 403, "detail": "Balance is 30 but the transfer requires 50.", "instance": "/accounts/123/transfers/abc" }

Q30.
What is the purpose of a 409 Conflict, and in what scenario would you return it?

Mid

409 Conflict indicates the request is valid but can't be completed because it conflicts with the current state of the resource, so the client may be able to resolve it and retry.

  • Typical scenarios:

    • Optimistic concurrency: a stale If-Match/ETag means someone else updated the resource first (lost-update prevention).

    • Uniqueness violations: creating a user with an email that already exists.

    • Illegal state transitions: cancelling an order that's already shipped.

  • How it differs from neighbors:

    • 400 means the request itself is malformed; 409 means the request is well-formed but clashes with current state.

    • 422 is for semantically invalid content rather than a state conflict.

  • Best practice: Explain the conflict in the body so the client knows what to reconcile before retrying.

Q31.
What is the correct status code for a request that is syntactically correct but violates business logic?

Mid

Return 422 Unprocessable Entity: the request is well-formed and the syntax is valid, but the server can't process it because it breaks a semantic or business rule.

  • Why 422 fits:

    • Defined (RFC 4918) for requests that are syntactically correct but semantically erroneous.

    • Example: a transfer request whose amount exceeds the account balance: valid JSON, invalid business outcome.

  • Why not 400: 400 Bad Request implies malformed syntax the server cannot even parse.

  • Alternatives some teams prefer:

    • 409 Conflict when the rule is about resource state (e.g. duplicate, version conflict).

    • The key: always include a clear error body explaining which rule failed.

Q32.
What is the difference between a 400 Bad Request and a 422 Unprocessable Entity, and when would you use each?

Mid

Use 400 when the request itself is malformed (bad syntax the server can't parse), and 422 when the syntax is valid but the content fails validation or semantic rules.

  • 400 Bad Request:

    • Server cannot understand the request: invalid JSON, missing required structure, malformed query string.

    • The parser fails before any business logic runs.

  • 422 Unprocessable Entity:

    • Syntax is fine and parsed successfully, but values are invalid (e.g. email format wrong, negative age, field constraint violated).

    • FastAPI returns 422 automatically when Pydantic validation fails.

  • Practical note: Many APIs (and some frameworks) use 400 for both; just be consistent and return a detailed error body either way.

Q33.
What status code should you return when a client exceeds a rate limit, and how do headers like Retry-After help?

Mid

Return 429 Too Many Requests when a client exceeds its rate limit, and include a Retry-After header so the client knows exactly how long to wait before trying again.

  • 429 Too Many Requests: Signals the client has sent too many requests in a given window; it's a client-side 4xx error.

  • Retry-After:

    • Tells the client when to retry, as a number of seconds (Retry-After: 60) or an HTTP date.

    • Lets well-behaved clients back off automatically instead of hammering the server.

  • Complementary headers: X-RateLimit-Limit, X-RateLimit-Remaining, and X-RateLimit-Reset expose quota state proactively, before a 429 hits.

Q34.
When should an API return a 500 Internal Server Error versus a 503 Service Unavailable?

Mid

Use 500 for an unexpected, unhandled failure inside your code, and 503 when the server is healthy but temporarily unable to handle the request (overloaded or down for maintenance).

  • 500 Internal Server Error:

    • A bug or unhandled exception: null dereference, uncaught error, broken logic.

    • Generic catch-all; the client can't fix it and retrying usually won't help.

  • 503 Service Unavailable:

    • A temporary, expected condition: overload, deployment, dependency outage, maintenance window.

    • Implies the problem is transient, so pair it with a Retry-After header.

  • Rule of thumb: 500 = "something broke that shouldn't have"; 503 = "working fine, just not right now."

Q35.
How do you handle resource hierarchy in URIs, and when should you use nesting versus flat structures with query parameters?

Mid

Use nesting to express a genuine ownership/containment relationship, but keep it shallow (one level is usually enough) and switch to flat URIs with query parameters for filtering, cross-cutting access, or when a resource has its own identity.

  • Nest for true parent-child ownership:

    • /users/42/orders reads naturally as "orders belonging to user 42."

    • Limit depth: avoid /users/42/orders/7/items/3/reviews; it's brittle and hard to read.

  • Go flat when the resource stands alone: Once an order has a global ID, /orders/7 is cleaner than /users/42/orders/7.

  • Use query params for filtering and relationships:

    • /orders?user_id=42&status=open filters a flat collection without deep nesting.

    • Reserve the path for identity, the query string for refinement (filter, sort, paginate).

  • Rule of thumb: Nest one level to show containment; flatten plus query params for everything else.

Q36.
How would you design a RESTful URI for a search feature? Should it be a resource or a query parameter?

Mid

Treat search as a query parameter on a collection, not a separate resource: search is a way of filtering an existing collection, so GET /products?q=phone is more RESTful than /search.

  • Prefer query parameters on the resource collection:

    • e.g. GET /products?q=phone&category=electronics&sort=price: results are still a list of products.

    • Keeps the URL cacheable, bookmarkable, and idempotent under GET.

  • When a dedicated search resource is justified:

    • Cross-resource or global search (e.g. GET /search?q=... spanning users, posts, and files).

    • Complex query payloads too large for a URL: use POST /searches with a body, optionally returning a reusable search resource.

  • Avoid verbs in the path: /getProducts or /products/search as an action are less RESTful than filtering the collection itself.

Q37.
What is Content Negotiation and how do the Accept and Content-Type headers work together?

Mid

Content negotiation lets the client and server agree on the representation format of a resource. The client states what it wants with Accept, and the server (or client, on a write) declares what it actually sent with Content-Type.

  • Accept: what the client wants back:

    • Sent on the request: Accept: application/json asks the server to respond in JSON.

    • Supports quality weights for preferences: Accept: application/json;q=0.9, text/xml;q=0.5.

  • Content-Type: what the payload actually is:

    • Describes the body in a request (POST/PUT) or a response.

    • The server parses the request body according to this header.

  • How they work together:

    • Server picks a representation matching Accept and labels its response with the matching Content-Type.

    • If nothing acceptable can be produced, respond 406 Not Acceptable; an unsupported request body type gets 415 Unsupported Media Type.

Q38.
How would you design a RESTful endpoint to support filtering, sorting, and pagination for a large collection?

Mid

Expose filtering, sorting, and pagination as query parameters on the collection GET endpoint, keeping the resource URL clean and the operation idempotent and cacheable. Combine them freely on a single endpoint.

  • Filtering:

    • Field-based query params: GET /orders?status=shipped&country=US.

    • For ranges/operators use a clear convention: ?price_gte=100&price_lte=500 or ?created[gt]=2024-01-01.

  • Sorting:

    • A sort param with direction: ?sort=-created_at,name (leading - for descending).

    • Whitelist sortable fields to protect indexes and prevent abuse.

  • Pagination:

    • Offset style: ?page=2&size=20; cursor style: ?limit=20&cursor=abc123.

    • Always cap size with a sane maximum to avoid huge responses.

  • Cross-cutting concerns:

    • Validate and whitelist all params; return 400 on unknown or malformed values.

    • Ensure backing indexes exist for filterable/sortable columns.

text

GET /orders?status=shipped&price_gte=100&sort=-created_at&page=2&size=20

Q39.
What metadata should a paginated API response include to help clients navigate large collections?

Mid

A paginated response should include enough metadata for a client to know where it is, how big the result set is, and how to fetch the next/previous pages without guessing.

  • Navigation links:

    • next, prev, first, last URLs (HATEOAS-style) so the client follows links rather than building them.

    • For cursors, include the next_cursor (and a has_more boolean).

  • Position and size:

    • Current page and page_size (offset style).

    • total_count and total_pages when feasible (note: exact counts can be expensive on huge tables).

  • Where to put it: In the body under a meta/links envelope, or in headers like Link and X-Total-Count.

json

{ "data": [ /* items */ ], "meta": { "page": 2, "page_size": 20, "total_count": 137, "total_pages": 7 }, "links": { "next": "/orders?page=3&size=20", "prev": "/orders?page=1&size=20" } }

Q40.
How do you handle API versioning, and what are the tradeoffs of URI, header, and media type versioning?

Mid

Versioning lets you evolve an API without breaking existing clients: you pick a strategy (URI, header, or media type) to signal which contract a request expects, then maintain old versions until clients migrate.

  • URI versioning:

    • Version in the path, e.g. /v1/users.

    • Pros: highly visible, trivially cacheable and routable, easy to test in a browser.

    • Cons: violates URI-identifies-a-resource purity (same resource has many URIs), and clients must rewrite URLs to upgrade.

  • Header versioning:

    • Custom header like X-API-Version: 2.

    • Pros: keeps URIs clean and stable across versions.

    • Cons: less discoverable, harder to test by hand, and caches must vary on the header.

  • Media type (content negotiation) versioning:

    • Version in Accept, e.g. application/vnd.myapp.v2+json.

    • Pros: most RESTful (the resource URI is stable, the representation is negotiated).

    • Cons: most complex, poor tooling/browser support, easy to get wrong.

  • General tradeoff: simplicity and visibility (URI) versus purity and URI stability (header/media type). Most public APIs choose URI versioning for pragmatism.

Q41.
What are the pros and cons of URI versioning versus Header versioning?

Mid

URI versioning puts the version in the path and optimizes for visibility and tooling; header versioning keeps URIs clean and optimizes for REST purity at the cost of discoverability.

  • URI versioning pros:

    • Explicit and obvious: /v1/orders tells you the version at a glance.

    • Easy to browse, bookmark, log, and route; caches naturally key on the full URL.

  • URI versioning cons:

    • The same logical resource lives at multiple URLs, which purists argue breaks resource identity.

    • Clients must change every URL to upgrade.

  • Header versioning pros:

    • URIs stay clean and stable across versions (one canonical resource URL).

    • Upgrading can be as simple as changing a header value.

  • Header versioning cons:

    • Not discoverable: you can't see the version in the URL or test it in a browser easily.

    • Caches and proxies must honor Vary on that header or risk serving the wrong version.

  • Bottom line: pick URI for public-facing simplicity, header for clean internal APIs where clients are sophisticated.

Q42.
What is an ETag, and how does it help with optimistic concurrency or caching?

Mid

An ETag is an opaque identifier (a version fingerprint) a server attaches to a representation in the ETag response header; clients echo it back to ask "has this changed?" for caching, or "is this still current?" for safe updates.

  • What it is:

    • A hash or version token representing a specific state of a resource.

    • Strong ETags mean byte-identical; weak ETags (W/"...") mean semantically equivalent.

  • Caching use (with If-None-Match): Client sends its cached ETag in If-None-Match; if unchanged the server returns 304 Not Modified with no body, saving bandwidth.

  • Concurrency use (with If-Match): Client sends the ETag it last read in If-Match on a write; the server rejects with 412 Precondition Failed if the resource changed meanwhile.

http

GET /users/42 200 OK ETag: "a1b2c3" # later, revalidate GET /users/42 If-None-Match: "a1b2c3" 304 Not Modified

Q43.
Explain the difference between the Cache-Control directives no-cache and no-store.

Mid

Both control caching but differ in whether storing is allowed: no-store forbids keeping any copy at all, while no-cache allows storing but requires revalidation with the origin before reuse.

  • no-store:

    • Caches must not write the request or response to disk or memory at all.

    • Use for sensitive data (banking, personal info) where no trace should persist.

  • no-cache:

    • A cached copy may be stored, but it must be revalidated (via ETag/If-None-Match or Last-Modified) before being served.

    • Enables cheap 304 responses while guaranteeing freshness.

  • Common confusion: the name no-cache does not mean "don't cache"; it means "don't use without checking."

Q44.
How can ETags be used for "Optimistic Concurrency Control"?

Mid

ETags enable optimistic concurrency by acting as a version check on writes: the client must prove it is updating the version it last read, otherwise the server rejects the change so a stale overwrite (lost update) can't happen.

  1. Read and capture the version: A GET returns the resource with an ETag header.

  2. Write conditionally: The client sends If-Match: "<etag>" on the PUT/PATCH/DELETE.

  3. Server decides:

    • If the current ETag still matches, apply the change and return a new ETag.

    • If it differs (someone edited in between), return 412 Precondition Failed and the client re-reads and retries.

  • Optimistic: no locks are held; conflicts are detected only at write time, which scales well when collisions are rare.

  • Contrast: pessimistic locking blocks others up front, but harms concurrency and is awkward over stateless HTTP.

http

PUT /docs/9 If-Match: "v7" Content-Type: application/json { "title": "Updated" } # if server's current ETag != "v7": 412 Precondition Failed

Q45.
How does HTTP caching work for APIs, and what role do Cache-Control directives play?

Mid

HTTP caching lets clients and intermediaries reuse responses instead of refetching; Cache-Control is the primary header that tells them whether a response may be stored, for how long, and whether it must be revalidated.

  • Two phases of caching:

    • Freshness: while within its lifetime a cached copy is served directly with no network call.

    • Validation: once stale, the cache revalidates with the origin using ETag/If-None-Match or Last-Modified/If-Modified-Since, often getting a cheap 304.

  • Key Cache-Control directives:

    • max-age=N: seconds the response stays fresh.

    • public vs private: shareable by proxies/CDNs vs only the end client.

    • no-cache: store but revalidate before use; no-store: never store.

    • must-revalidate: once stale, do not serve without successful revalidation.

  • For APIs:

    • Cache mostly GET responses; mutations should not be cached.

    • Use Vary (e.g. on Accept or auth) so caches don't serve the wrong representation.

Q46.
Explain the difference between Basic Auth, API Keys, and JWT/OAuth2, and when is each appropriate?

Mid

All three authenticate requests but differ in what they identify and how much trust/flexibility they carry: Basic Auth sends raw credentials per request, API Keys identify an application, and JWT/OAuth2 issues scoped, expiring tokens suited to delegated, third-party access.

  • Basic Auth:

    • Sends Authorization: Basic base64(user:pass) on every request (base64 is encoding, not encryption, so HTTPS is mandatory).

    • Simple, but credentials travel constantly and there's no scoping or expiry; best for internal tools or quick prototypes.

  • API Keys:

    • An opaque token (in a header or query) identifying the calling app/project rather than a user.

    • Good for server-to-server access and rate limiting; weak on fine-grained authorization and easy to leak if embedded in clients.

  • JWT / OAuth2:

    • OAuth2 is the delegation framework (an authorization server issues access tokens after consent); JWT is a common self-contained token format carrying claims and a signature.

    • Supports scopes, expiry, and third-party access without sharing passwords; more moving parts (token issuance, refresh, revocation).

  • Choosing:

    • Internal/simple: Basic Auth over TLS.

    • Identifying apps / public read APIs: API Keys.

    • User login, mobile/SPA, or third-party delegated access: OAuth2 with JWT.

Q47.
What are OAuth scopes and how are they used to limit what an API client can access?

Mid

Scopes are named permissions a client requests and a user consents to, limiting what the issued access token can do. They enforce least privilege: a token only carries the access it actually needs.

  • What they are: Space-separated strings like read:orders or profile email sent in the authorization request.

  • How they're enforced:

    • The user consents to the requested scopes; the auth server encodes granted scopes into the token.

    • The resource server checks the token's scopes per endpoint and returns 403 if a required scope is missing.

  • Why they matter:

    • Least privilege: a read-only client never receives write access.

    • Limit blast radius if a token leaks.

  • Caveat: Scopes are coarse-grained authorization, not a replacement for resource-level checks (e.g. ownership of a specific record).

Q48.
What is the role of refresh tokens, and how do they improve the security of token-based authentication?

Mid

A refresh token is a long-lived credential used solely to obtain new short-lived access tokens without forcing the user to log in again. It lets access tokens expire quickly (limiting the damage of a leak) while keeping the user logged in.

  • The core tradeoff it enables:

    • Access tokens stay short-lived (minutes), so a stolen one expires fast.

    • The refresh token (sent only to the auth server) gets a fresh access token when the old one expires.

  • Security advantages:

    • It's transmitted rarely (only to the token endpoint), reducing exposure.

    • It can be revoked server-side, instantly ending a session.

  • Hardening practices:

    • Refresh token rotation: issue a new one on each use and invalidate the old.

    • Reuse detection: if a rotated token is replayed, revoke the whole family (signals theft).

    • Store securely (HttpOnly cookie or secure native storage), never in JS-readable storage.

Q49.
What is "API-First Design" and why is it beneficial for teams?

Mid

API-First Design means you define and agree on the API contract (its endpoints, schemas, and behaviors) before writing implementation code, treating the contract as the source of truth. Teams build against the spec in parallel instead of waiting on a backend.

  • The contract comes first:

    • Written as a machine-readable spec (e.g. OpenAPI) and reviewed before coding begins.

    • Contrast with code-first, where docs are generated after the implementation already exists.

  • Why teams benefit:

    • Parallel work: frontend uses mock servers from the spec while backend implements it.

    • Consistency: shared conventions across services reduce divergent designs.

    • Tooling: generate client SDKs, server stubs, validation, and docs from one source.

    • Early feedback: design flaws surface in review, not after expensive implementation.

  • Caveat: It requires discipline to keep the spec and implementation in sync (contract testing helps).

Q50.
What is OpenAPI (Swagger), and how does it help in documenting and contracting a REST API?

Mid

OpenAPI (formerly Swagger) is a language-agnostic specification for describing a REST API in a machine-readable format (usually YAML or JSON): it defines endpoints, parameters, request/response schemas, auth, and status codes so humans and tools share one source of truth.

  • A formal contract: Describes paths, methods, schemas, and responses so client and server agree before code is written (contract-first or design-first).

  • Drives tooling and automation:

    • Interactive docs render automatically (Swagger UI, Redoc).

    • Generate client SDKs, server stubs, and mock servers from the same spec.

    • Enables request/response validation and contract testing in CI.

  • Swagger vs OpenAPI: "Swagger" is the old name plus the tooling ecosystem; "OpenAPI" is the specification standard (3.x today).

  • Frameworks can auto-generate it: FastAPI exposes the spec at /openapi.json and serves docs at /docs, keeping documentation in sync with code.

Q51.
How do you approach validating incoming requests in a REST API, and where should validation happen?

Mid

Validate at the edge as input enters the system, rejecting malformed requests early with a clear 4xx, then enforce business rules deeper in the service layer. Schema validation and business validation are distinct concerns and belong in different places.

  • Syntactic/schema validation at the boundary:

    • Check types, required fields, formats, ranges, and enums as the request is deserialized.

    • Use declarative models (Pydantic, JSON Schema) so it's consistent and self-documenting.

  • Semantic/business validation in the service layer:

    • Rules needing state or context: "email already exists", "balance sufficient", "order can still be cancelled".

    • Keep this out of the controller so logic stays testable and reusable.

  • Never trust the client:

    • Always re-validate server-side even if the frontend validates; client checks are UX, not security.

    • Validate path/query params and headers, not just the body.

  • Return useful errors: Use 422/400 with a structured body listing which fields failed and why.

Q52.
How would you approach testing a REST API, and what types of tests are important?

Mid

Test an API as a pyramid: many fast unit tests, fewer integration tests that hit real collaborators (DB, framework), and a small set of end-to-end tests over HTTP. The goal is confidence that the contract and behavior hold, not just code coverage.

  • Unit tests: Test business logic and validation in isolation with dependencies mocked; fast and numerous.

  • Integration tests:

    • Exercise the route through the framework against a real DB (or a test container) to catch wiring, serialization, and query bugs.

    • Use a test client (e.g. TestClient) so you go through the full request/response stack.

  • Contract tests: Verify responses match the OpenAPI schema / consumer expectations so you don't silently break clients.

  • End-to-end tests: A few flows over real HTTP against a deployed environment; high confidence but slow and brittle, so keep them few.

  • What to actually assert:

    • Status codes, response body shape, headers, error cases, and auth (401/403), not just the happy path.

    • Edge cases: invalid input, missing auth, pagination, idempotency.

Q53.
What is CORS (Cross-Origin Resource Sharing), and why is it a browser-level security feature rather than a server-level one?

Mid

CORS is a mechanism where a server uses HTTP headers to tell the browser which other origins are allowed to read its responses, relaxing the browser's default Same-Origin Policy. It's a browser-enforced safety check, not a server-side access control: it protects users, not your API.

  • Same-Origin Policy is the baseline: By default a page can't read responses from a different origin (scheme + host + port), preventing a malicious site from reading your bank's API using your cookies.

  • CORS selectively relaxes it:

    • The server returns Access-Control-Allow-Origin and related headers to opt specific origins in.

    • For unsafe methods/headers the browser sends a preflight OPTIONS request first to ask permission.

  • Why it's browser-level:

    • Only browsers enforce it; the browser blocks the JS from reading the response, the request may still reach the server.

    • cURL, Postman, and server-to-server calls ignore CORS entirely.

  • Key implication: CORS is not authentication or authorization; never rely on it to secure data. Use it to control which web frontends may call you, and still enforce real auth server-side.

Q54.
What is injection (e.g. SQL injection) in the context of APIs, and how do you defend against it?

Mid

Injection happens when untrusted input is interpreted as part of a command or query (SQL, NoSQL, OS shell, LDAP), letting an attacker alter logic, read/modify data, or run arbitrary code. The fix is to never mix data with code: separate them so input is always treated as a value.

  • How it works:

    • Input is concatenated into a query string, e.g. ' OR '1'='1 turns a login check into an always-true condition.

    • Not just SQL: NoSQL operators, OS command injection, and LDAP injection follow the same pattern.

  • Primary defense: parameterized queries:

    • Use prepared statements / bound parameters so the driver sends query and data separately and the data can never become executable code.

    • Prefer a vetted ORM or query builder, which parameterizes by default.

  • Defense in depth:

    • Validate and constrain input (type, length, allowlist) at the API boundary.

    • Least privilege DB accounts so a breach can't drop tables or read everything.

    • Escape output and avoid building shell commands from input; if unavoidable, use safe APIs that take argument arrays.

python

# Bad: string concatenation cur.execute("SELECT * FROM users WHERE email = '" + email + "'") # Good: parameterized query cur.execute("SELECT * FROM users WHERE email = %s", (email,))

Q55.
What are the main tradeoffs between REST and GraphQL? When would you choose one over the other?

Mid

REST exposes many resource endpoints with fixed response shapes; GraphQL exposes one endpoint where clients request exactly the fields they need. REST shines for cacheable, resource-oriented APIs; GraphQL shines when clients have varied, nested data needs and you want to avoid over/under-fetching.

  • Data fetching:

    • REST: server defines the response shape, so clients may over-fetch or make multiple round trips (under-fetching).

    • GraphQL: the client picks fields and traverses relations in one query.

  • Caching:

    • REST: leverages HTTP caching, CDNs, and ETag easily via URLs and verbs.

    • GraphQL: usually a single POST endpoint, so HTTP caching is harder; needs client-side or persisted-query caching.

  • Versioning and schema:

    • GraphQL has a strong typed schema and evolves by adding/deprecating fields rather than versioning.

    • REST commonly versions via URL or headers.

  • Complexity and risk:

    • GraphQL needs guardrails: query depth/complexity limits and dataloaders to avoid N+1 and abusive queries.

    • REST is simpler operationally and easier to monitor per endpoint.

  • When to choose:

    • REST: public APIs, simple CRUD, heavy caching needs, file uploads.

    • GraphQL: diverse clients (mobile + web), deeply nested data, rapidly evolving frontend requirements.

Q56.
What are the downsides of REST, including over-fetching, under-fetching, and the N+1 problem?

Mid

REST's fixed, resource-oriented responses mean clients often get too much or too little data, and chaining related calls can multiply requests. The main pain points are over-fetching, under-fetching, and the N+1 problem, all stemming from the server (not the client) deciding response shape.

  • Over-fetching:

    • An endpoint returns more fields than the client needs (e.g. the full user object when you only want a name), wasting bandwidth.

    • Partial mitigation: sparse fieldsets via query params like ?fields=name,email.

  • Under-fetching:

    • One endpoint doesn't return enough, so the client makes additional calls to assemble a view.

    • Mitigation: compound/aggregate endpoints or embedding related resources.

  • N+1 problem:

    • Fetching a list, then one request per item for related data: 1 + N calls (client-side) or 1 + N DB queries (server-side).

    • Mitigation: batch endpoints, eager-loading/joins on the server, or a dataloader pattern.

  • Other downsides:

    • Versioning churn as resource shapes change.

    • Many round trips for nested data, which GraphQL or BFF (backend-for-frontend) layers often address.

Q57.
What are the main differences between REST and SOAP, and when might SOAP still be preferred?

Mid

REST is an architectural style using HTTP verbs and resources, typically with lightweight JSON; SOAP is a strict XML-based messaging protocol with built-in standards for security, transactions, and contracts. REST is simpler and dominant for web/mobile APIs; SOAP still appears in enterprise, financial, and legacy systems needing formal contracts and message-level guarantees.

  • Format and style:

    • REST: resource-oriented, any format (usually JSON), uses HTTP verbs and status codes.

    • SOAP: XML-only envelopes, operation-oriented, transport-agnostic (HTTP, SMTP, etc.).

  • Contract:

    • SOAP has a rigid WSDL contract and strong typing.

    • REST is looser, optionally described by OpenAPI.

  • Built-in standards (WS-*):

    • SOAP offers WS-Security, WS-AtomicTransaction, and reliable messaging at the message level.

    • REST relies on HTTPS/transport-level security and external mechanisms.

  • Overhead: SOAP's XML envelopes are verbose and heavier; REST/JSON is lighter and faster to parse.

  • When SOAP still fits: Enterprise integrations needing formal contracts, message-level security, or ACID-style transactional guarantees (banking, telecom, government legacy).

Q58.
What is the difference between a REST API and an RPC-style API?

Mid

A REST API models the domain as resources (nouns) manipulated with standard HTTP verbs, while an RPC-style API exposes actions (verbs/procedures) you call directly. REST says "act on this thing"; RPC says "run this function."

  • Resources vs procedures:

    • REST: GET /users/123, DELETE /users/123 act on a resource.

    • RPC: POST /getUser, POST /deleteUser name an operation.

  • Use of HTTP:

    • REST uses verbs and status codes semantically (idempotency, caching follow from this).

    • RPC often tunnels everything through POST and uses HTTP as a transport only.

  • URL design:

    • REST URLs identify entities; the verb is the HTTP method.

    • RPC URLs embed the action name; the method is incidental.

  • Fit:

    • REST suits CRUD and cacheable resource models.

    • RPC suits action-centric operations that don't map cleanly to resources (e.g. transfer, sendEmail); gRPC is a modern RPC example.

Q59.
How do you design a RESTful API to handle bulk or batch operations?

Mid

Model the batch as an action on a collection: POST a list of items (or operations) to a dedicated endpoint, then return a structured response describing the outcome of each one. The main design choices are the payload shape, atomicity, and how results are reported.

  • Endpoint design:

    • Use POST /resources/batch or POST a collection with an array body; avoid abusing PUT on a single resource.

    • For mixed operation types, accept a list of operations each with a method/verb and payload (similar to JSON Patch).

  • Atomicity: Decide all-or-nothing (transaction) vs best-effort, and document it clearly so clients know retry behavior.

  • Response shape: Return 207 Multi-Status or 200 with a results array carrying per-item id, status, and error.

  • Scale and safety:

    • Cap batch size and validate it (e.g. reject more than N items with 413 or 422).

    • Support idempotency keys so retried batches don't double-apply.

    • For very large or slow jobs, go async: return 202 Accepted with a status URL the client polls.

json

POST /v1/users/batch { "items": [ { "name": "Ann", "email": "ann@x.com" }, { "name": "Bo", "email": "bo@x.com" } ] }

Q60.
What is the "Uniform Interface" constraint and can you explain its four sub-constraints?

Senior

The Uniform Interface is the central REST constraint requiring a single, consistent way for clients and servers to interact regardless of implementation. It is defined by four sub-constraints that together decouple client from server.

  • Identification of resources: Each resource has a stable identifier (a URI); the resource is conceptually separate from its representation.

  • Manipulation through representations: Clients act on resources by exchanging representations (JSON, XML); holding one gives enough info to modify or delete the resource.

  • Self-descriptive messages: Each message includes enough metadata (method, Content-Type, cache headers) to be understood in isolation.

  • HATEOAS: Hypermedia drives state: responses include links to available next actions.

  • Why it matters: Uniformity lets generic tooling, caches, and proxies work, and lets client and server evolve independently, at the cost of some efficiency.

Q61.
What is HATEOAS and why would a developer choose not to implement it in a modern production environment?

Senior

HATEOAS (Hypermedia As The Engine Of Application State) embeds links in responses so clients discover available actions dynamically instead of hardcoding URIs. Despite being the hallmark of "true" REST, many teams skip it in production because the cost and complexity rarely pay off for their clients.

  • What it gives you: Decoupling from URI structure and a self-describing, discoverable API (Richardson Level 3).

  • Why teams skip it:

    • Client reality: most clients are coded against fixed, documented endpoints and ignore the links anyway.

    • Complexity and payload bloat: generating and parsing link relations adds work on both sides.

    • Tooling gap: few client libraries truly navigate hypermedia, so the theoretical decoupling goes unused.

    • Alternatives exist: API versioning, OpenAPI/Swagger docs, and SDKs solve discoverability more practically.

  • Pragmatic stance: Most production "REST" APIs settle at Level 2: correct verbs and status codes, no hypermedia, by deliberate trade-off.

Q62.
How do you design an API to be 'discoverable' without requiring the client to have hardcoded URLs for every sub-resource?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q63.
What is 'code on demand' in REST, and why is it an optional constraint?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q64.
What are media types in REST, and how can custom media types support hypermedia and versioning?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q65.
What is an "Idempotency Key" and how does it prevent duplicate side effects in distributed systems?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q66.
Is PATCH idempotent, and why can it be idempotent in some designs but not in others?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q67.
How do you design a RESTful endpoint for an action that isn't a CRUD operation, such as canceling an order or promoting a user?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q68.
Explain the difference between 'Rate Limiting' and 'Throttling.' How would you design a strategy for both?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q69.
Explain the difference between Offset-based and Cursor-based pagination, and in what scenarios is cursor-based strictly better?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q70.
How do you handle breaking changes in a REST API while maintaining backward compatibility?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q71.
What is the 'Expand and Contract' pattern for introducing breaking changes without a version bump?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q72.
What are the security implications of using JWTs for API authentication compared to traditional Session Cookies?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q73.
Can you explain how the OAuth 2.0 authorization code flow works and what the different grant types are?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q74.
What is the difference between OAuth 2.0 and OpenID Connect?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q75.
How do you design a "frontend-friendly" API contract?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q76.
How do you monitor and observe a REST API in production, and what role do correlation IDs and tracing play?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q77.
What is "Broken Object Level Authorization" (BOLA/IDOR) and why is it the #1 risk on the OWASP API Security Top 10?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q78.
What is Mass Assignment (Overposting) and how do you design an API to prevent users updating fields they shouldn't?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q79.
What are the main differences between REST and gRPC for internal microservices?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q80.
When would you choose REST for external-facing APIs over gRPC?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q81.
How do you design a RESTful API to handle long-running background tasks without blocking the client?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q82.
What are the trade-offs between using Webhooks versus Polling for real-time updates?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.

Q83.
How do you handle 'Partial Failures' in a bulk or batch operation?

Senior
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.