Skip to content
System Design

API Design interview questions and answers

50 questions, 15 with code. About 4 h 43 min to read them all.

By TestLab · Updated

Plan for an interview
50 questions

Track what you know and what to revise.

Sign in to track progress

You can open a few full answers without signing in. Sign in to read all

1

What defines an API and what are its core purposes?

An API (Application Programming Interface) is a defined contract between a client and a provider that specifies exactly how requests can be made to access functionality or data, without exposing the internal implementation of either side.

Read full answer

Applies toall versions

Problem It Solves

Before a formal API, systems often had to be directly coupled to share capabilities, such as reading from another system’s database or calling internal functions. This created brittle integrations, made changes unsafe, and blurred boundaries between systems. An API solves this by enforcing a clear boundary: the provider decides what is exposed, and the consumer only needs to follow that contract.

Core Purposes

  • Abstraction: Hides complex internal logic. For example, an e-commerce checkout doesn’t need to know how a payment service tokenizes cards, it only needs to know how to call the payment API.

  • Integration: Allows completely separate systems to work together over a network. A chat app can integrate with a notification service without merging their codebases.

  • Reusability: A single API can be consumed by a web app, a mobile app, and even third parties, preventing the same functionality from being rebuilt multiple times.

  • Controlled access: Provides a place to enforce authentication, authorization, and restrictions on what data or actions a consumer can take.

  • Decoupling for independent evolution: Teams can refactor or scale their internal systems without forcing all consumers to change, as long as the API contract remains compatible.

Trade-offs

  • Latency: Any API call over a network is orders of magnitude slower than an in-process call (same-datacenter round trip ~0.5 ms rough order of magnitude). This cost is unavoidable when crossing system boundaries.

  • Operational complexity: Exposing an API introduces the need for availability, versioning, error handling, rate limiting, and monitoring.

  • Contract rigidity: Breaking the contract impacts every consumer at once. Versioning becomes necessary the moment multiple consumers exist.

  • Exposure of risk: Every exposed endpoint is an attack surface. Without proper access control, the API can leak data or allow unintended actions.

  • Workload-dependent payoff: For a single, tightly owned monolith with one consumer, creating a public API contract can be pure overhead. It’s only worth it when you genuinely need separation, reuse, or integration.

Real-World Example

Take a URL shortener. The redirect service doesn’t need the web frontend to know how it generates short keys or where mappings are stored. The frontend calls the URL shortener API with a long URL and gets back a short link. If the backend switches storage or changes its key generation strategy, the frontend remains unchanged, so long as the request and response shape stays the same.

What Interviewers Look For

  • Contract mindset: Seeing the API as a contract, not just “an HTTP endpoint”.

  • Awareness of boundaries: Knowing when to draw them and that crossing them has a cost.

  • Failure-aware thinking: Recognizing that APIs fail over networks (timeouts, errors, partial failures), unlike local function calls.

  • Common mistake: Treating an API as a way to “just expose everything”, instead of deliberately choosing what to expose with access control and stability in mind.

2

What is the difference between an API and a web service?

An API is any defined contract that allows one software component to interact with another, while a web service is a specific type of API that is exposed over a network using standard web protocols.

Read full answer

Applies toall versions

Core Distinction

The key difference is scope: all web services are APIs, but not all APIs are web services.

  • API: A broad term. It can be local (in-process), such as a library or an interface used within the same runtime, or remote, such as one reached over a network. Communication can be via direct function calls, inter-process communication, or network requests.

  • Web service: A remote API that is reachable over a network, most often using HTTP(S). Its defining trait is network accessibility, not who consumes it.

Side-By-Side Comparison

Aspect API Web Service
Scope General. Can be in-process or network-based. Narrow. Always network-based.
Transport Any medium (direct function calls, IPC, sockets, HTTP(S), etc.) Network protocols, most often HTTP(S). Examples include SOAP or REST over HTTP(S).
Dependencies No requirement for a network or a listening endpoint. Requires a network-accessible endpoint. This may be provided by a web server, a reverse proxy, an API gateway, or a serverless function.
Examples The List interface in Java, a language standard library, or an internal module interface. A SOAP-based tax calculation endpoint, or a REST endpoint returning JSON over HTTPS.

Where This Fits In Real Systems

For example, in an e-commerce checkout, a PaymentGateway interface used internally between modules is an in-process API. Calling a third-party provider’s HTTPS endpoint to authorize a card uses that provider’s remote API exposed as a web service. Both are APIs by definition; only the second is a web service.

Trade-Offs To Know

  • Simplicity vs reach: An in-process API has near-zero network cost (rough order of magnitude: tens of ns), but only works within the same runtime. A web service is reusable across clients and teams, but adds network latency (same-datacenter ~0.5 ms, cross-region ~50-150 ms, rough orders of magnitude).

  • Control vs exposure: Web services require extra concerns (authentication, rate limiting, availability, and failure handling) that in-process APIs rarely have.

  • Coupling: Exposing a web service creates a cross-network contract. Versioning and backward compatibility become mandatory the moment other systems depend on it.

Common Pitfall

Treating the terms as interchangeable. The correct distinction: a web service is a subset of APIs that communicates over a network (most often over the web), whereas an API is the general concept of programmatic communication regardless of location.

3

What principles guide the design of a RESTful API?

A RESTful API is an API organized around identifiable resources and manipulated through a uniform HTTP interface. Its defining constraints are stateless request processing, cacheable responses, a uniform interface, a layered system, and optional code-on-demand extensions.

Read full answer

Applies toREST over HTTP/1.1, HTTP/2, and HTTP/3

Core REST Constraints

  • Client-server separation: Clients own presentation and user-interface state, while servers own resources and business rules. This permits independent evolution, but the server cannot assume clients use a particular UI.

  • Statelessness: Each request must contain the information needed to process it, including authentication credentials. A server may store resource data, but it should not depend on hidden session state in one process. This improves horizontal scalability and caching, although it can require larger tokens or repeated authorization checks.

  • Cacheability: Responses should explicitly describe whether clients, proxies, or CDNs may store them. GET and HEAD are normally cacheable; Cache-Control, ETag, and Last-Modified support conditional requests.

  • Uniform interface: Resources use URIs, operations use HTTP methods, responses use standard status codes and media types, and relationships may be represented with hyperlinks.

  • Layered system: Clients need not know whether a request reaches the application directly or passes through a load balancer, API gateway, cache, or service boundary.

  • Optional code-on-demand: A server may extend functionality through links to executable representations, although most business APIs avoid this because it complicates clients and security review.

HTTP Semantics

HTTP methods communicate intent rather than merely naming application actions.

Method Safe Idempotent Typical use
GET Yes Yes Read a resource
HEAD Yes Yes Retrieve metadata only
POST No No Create or trigger non-idempotent processing
PUT No Yes Replace a resource completely
DELETE No Yes Remove a resource
PATCH No Not guaranteed Apply a partial modification
  • Safe means the client does not intend to change server state.

  • Idempotent means repeating the request has the same intended effect as performing it once. Responses can differ—for example, deleting an already deleted resource might return 404—but the final state is unchanged.

  • POST should not be treated as idempotent. A common Idempotency-Key header allows a client to retry a create operation safely, but this is an application convention rather than a universal HTTP guarantee.

Resource and Contract Design

  • Model business concepts as resources, using plural collection names such as /orders and /customers, with individual resources such as /orders/{orderId}.

  • Use HTTP methods instead of action-oriented endpoints such as /createOrder. Avoid verbs in URIs when the operation can be expressed through standard method semantics.

  • Return appropriate status codes: 201 Created for creation, 204 No Content for an empty successful response, 400 Bad Request for malformed requests, 422 Unprocessable Content for syntactically valid but semantically invalid input, 409 Conflict for state conflicts, 401 Unauthorized for missing or invalid authentication, 403 Forbidden for insufficient authorization, and 429 Too Many Requests for throttling.

  • Use application/problem+json for consistent error responses based on RFC 9457. Include a stable machine-readable error code, a safe human-readable message, and a request identifier without exposing internal stack traces.

  • Support pagination for collection endpoints. Offset pagination is simple but can skip or duplicate items when data changes; cursor pagination is more stable for large or frequently changing datasets.

  • Prefer additive, backward-compatible changes. URI versioning such as /v1/orders is visible and simple, while media-type versioning keeps version negotiation in the Accept header. REST itself does not mandate a versioning strategy.

Example Exchange

For example, a client can create an order with POST /v1/orders, a JSON content type, an Idempotency-Key header, and a body containing the customer ID and line items. The server can respond with 201 Created, a Location header pointing to /v1/orders/ord_789, and a JSON representation containing the order ID, status, customer ID, total, and currency.

The client can safely retry the same request with the same idempotency key if the first response is lost. The implementation must persist the key and resulting response so that concurrent or repeated requests do not create duplicate orders.

Trade-offs and Common Pitfalls

  • Stateless APIs scale well and work well with caches, but they may move session state into databases or token claims, adding latency and operational complexity.

  • Hypermedia improves discoverability and long-term evolvability, but many clients prefer explicit, stable schemas. This is a trade-off, not a requirement to hide every endpoint.

  • A pure resource model may be awkward for domain workflows or high-volume internal RPC. Public REST is often a stable contract over services that communicate internally with gRPC or messaging.

  • Common interview mistakes include treating POST as idempotent, using 200 for every result, omitting pagination, returning inconsistent errors, and designing a cache without an invalidation and freshness policy.

A strong answer emphasizes that REST is an architectural style, not a synonym for JSON over HTTP, and explains how each constraint improves scalability or evolvability while naming its operational cost.

4

How do SOAP and REST APIs differ?

SOAP is a standardized XML messaging protocol suited to formal, schema-governed integrations, while REST is an architectural style that exposes resources through a uniform interface, usually over HTTP. SOAP offers strong contracts and middleware interoperability; REST is often simpler to adopt and use but leaves more contract details for each API team to define.

Read full answer

Applies toSOAP 1.2 and REST-style APIs; examples use HTTP/1.1

Core Concepts

Both approaches solve the same broad problem: allowing independently developed systems to exchange business data reliably.

  • SOAP defines an envelope containing headers and a body. It is a protocol rather than an architectural style and can use HTTP, JMS, or other transport bindings.

  • REST represents domain concepts as resources identified by URLs. Clients interact through HTTP methods and receive representations, commonly JSON.

  • XML contracts: SOAP messages must be well-formed XML. A service can additionally define validity using XSD schemas, but XSD and DTDs are not required. XML payloads commonly use namespaces, XPath, and XSLT, although SOAP itself does not require them.

  • XML processing: DOM parsing loads a document into a tree and supports random access; SAX parsing processes it incrementally with lower memory usage.

  • REST payloads: REST does not mandate JSON. XML, JSON, CSV, and other media types are valid, although JSON dominates modern public APIs.

Feature Comparison

Concern SOAP API REST API
Model Operation-oriented messaging protocol Resource-oriented architectural style
Contract Commonly described with WSDL and schemas Often documented with OpenAPI; OpenAPI is optional
Payload XML in a SOAP envelope Usually JSON; the format is not mandated
HTTP behavior Almost always POST (SOAP 1.2 also defines GET for safe retrievals, rarely used); the body carries the operation result Uses standard methods, status codes, headers, and representations
Idempotency Depends on the operation contract GET, HEAD, PUT, and DELETE are idempotent; POST is not; PATCH is not guaranteed
Errors A SOAP Fault in the body; the SOAP 1.2 HTTP binding maps Sender faults to 400 and other faults to 500 HTTP status plus a structured body such as application/problem+json
Caching POST responses are not reused by shared HTTP caches, so caching is usually done in the application Can use HTTP validators, cache-control headers, and shared caches
Transport Protocol-independent Usually HTTP
Governance Strong support for generated clients and formal enterprise contracts Flexible, but teams must define validation, errors, pagination, and compatibility rules

Request and Response Examples

  • REST create request: POST /orders with Content-Type: application/json, Idempotency-Key: order-7f31, and body {"productId":"p-123","quantity":2}.

  • REST create response: HTTP/1.1 201 Created, Location: /orders/o-456, and body {"id":"o-456","status":"pending"}.

  • SOAP 1.2 create request: POST /soap/orders with Content-Type: application/soap+xml; charset=utf-8 and body <soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:ord="urn:example:orders"><soap:Body><ord:CreateOrder><ord:ProductId>p-123</ord:ProductId><ord:Quantity>2</ord:Quantity></ord:CreateOrder></soap:Body></soap:Envelope>.

  • SOAP 1.2 create response: HTTP/1.1 200 OK with Content-Type: application/soap+xml; charset=utf-8 and a SOAP body containing an ord:CreateOrderResponse with order ID o-456 and status pending.

Trade-offs and Selection

  • SOAP strengths: precise schemas, generated client code, strong enterprise middleware support, and extensible WS-* protocols. It fits regulated partnerships, heterogeneous enterprise systems, and environments already standardized around SOAP.

  • SOAP costs: larger XML messages, more parsing overhead, complex tooling, and a steeper learning curve. Schema evolution, namespace handling, and interoperability testing require additional effort.

  • REST strengths: concise resource models, HTTP interoperability, straightforward caching, and easy use from browsers, mobile clients, and command-line tools.

  • REST costs: the specification leaves validation, error formats, pagination, versioning, and compatibility behavior open. Without governance, independently designed REST APIs become inconsistent.

  • Network efficiency: JSON is often smaller and faster to parse than equivalent SOAP XML, but the difference depends on the payload and runtime.

  • Selection: use SOAP when formal contracts, generated clients, advanced WS-* interoperability, or an existing SOAP platform are important. Prefer REST for public APIs, resource-oriented domains, and clients benefitting from HTTP caching and tooling. Do not select SOAP merely because an integration is enterprise-oriented.

Best Practices and Pitfalls

  • For SOAP, publish versioned WSDL and schemas, generate clients where practical, use explicit namespaces, and configure XML parsers to disable DTDs and external entities to reduce XXE risk.

  • For REST, use plural resource names, correct HTTP methods and status codes, cursor pagination for large datasets, Idempotency-Key for retried POST requests, and application/problem+json for consistent errors.

  • Define caching validators, TTLs, and application-level invalidation rules; HTTP caching headers alone do not determine when changed domain data becomes stale.

  • Protect both styles with TLS, preferably TLS 1.3 where supported. SOAP’s WS-Security provides message-level controls but does not replace transport security.

  • Interviewers commonly look for the distinction that SOAP is a standardized messaging protocol, whereas REST is an architectural style. A common mistake is claiming that SOAP is always slower or that REST automatically provides security and scalability.

5

What is an API endpoint in API design?

An API endpoint is a specific network-accessible operation exposed by an API, identified by an HTTP method and a URL path. It forms part of the contract that clients use to retrieve, create, update, or delete data.

Read full answer

Applies toall API versions

How It Works

An API usually has a base URL, and clients append a resource path to it. For example:

  • Base URL: https://api.example.com/v1

  • Endpoint: GET /orders/123

  • Complete URL: https://api.example.com/v1/orders/123

The endpoint may also accept:

  • Path parameters: /orders/123 identifies a specific order.

  • Query parameters: /orders?status=shipped&limit=50 filters and paginates results.

  • Headers: Authorization and Content-Type carry authentication and format information.

  • Request body: usually used by POST and PATCH to send data.

The server validates the request, executes the operation, and returns a response containing a status code, headers, and usually a JSON body.

HTTP Method Semantics

The HTTP method defines what the endpoint is intended to do:

Method Typical purpose Idempotent?
GET Retrieve a resource Yes
POST Create a resource or trigger an operation No
PUT Replace a resource completely Yes
PATCH Partially update a resource Not guaranteed
DELETE Remove a resource Yes

GET, PUT, and DELETE are idempotent: repeating the same valid request has the same intended effect as performing it once. POST is not idempotent, which is why create operations often support idempotency keys. PATCH is not guaranteed to be idempotent unless the API explicitly defines it that way.

Request and Response Examples

A successful read might use:

  • Request: GET /v1/orders/123

  • Status: 200 OK

  • Body: {"id":"123","status":"shipped","total":49.99}

A successful creation might use:

  • Request: POST /v1/orders

  • Body: {"productId":"456","quantity":2}

  • Status: 201 Created

  • Response body: {"id":"789","status":"created"}

An invalid request should use a precise status code:

  • Request: POST /v1/orders

  • Status: 400 Bad Request for malformed JSON or missing required headers

  • Status: 422 Unprocessable Content for syntactically valid JSON that violates business rules

  • Error body: {"type":"https://api.example.com/problems/invalid-product","title":"Invalid product","status":422}

A rate-limited client receives 429 Too Many Requests, usually with a Retry-After header. Other important statuses include 401 for missing or invalid authentication, 403 for insufficient authorization, and 409 for a conflicting state.

Design Considerations

  • Use plural resource names: Prefer /orders over /getOrder.

  • Keep URLs resource-oriented: Put filtering, sorting, and pagination in query parameters rather than embedding many actions in paths.

  • Define an error contract: Prefer a consistent format such as RFC 9457 application/problem+json, including a stable error identifier and human-readable details.

  • Version deliberately: A new major version such as /v2 is appropriate for breaking changes; additive fields are usually backward-compatible.

  • Document behavior: Specify required parameters, authentication, validation rules, pagination, idempotency, rate limits, and error responses.

  • Do not expose internal structure: Endpoints should represent the domain contract, not leak database tables or implementation details.

An endpoint is more than a route in source code. It is a public compatibility boundary: changing its path, semantics, validation, or error behavior can break clients even when the underlying implementation remains unchanged. This adds maintenance cost, so stable resource modeling and explicit contracts are preferable to exposing a new endpoint for every internal action.

Common Interview Mistake

A common mistake is treating an endpoint as only a URL path. The complete contract also includes the HTTP method, parameters, authentication, authorization, validation, response schema, status codes, and failure behavior. Interviewers often ask how you would evolve or deprecate that contract without unexpectedly breaking clients.

6

Which HTTP methods are used in REST APIs?

The primary HTTP methods used in REST APIs are GET, POST, PUT, PATCH, and DELETE. They distinguish read, create, replace, partially update, and delete operations, while properties such as safety, idempotency, and cacheability determine how clients and intermediaries may cache or retry requests.

Read full answer

Applies toHTTP/1.1, HTTP/2, and HTTP/3

Common HTTP Methods

Method Purpose Safe Idempotent Typical success status
GET Retrieves a resource or collection Yes Yes 200 OK
POST Creates a resource or submits data for processing No No 201 Created, 200 OK, or 202 Accepted
PUT Creates or completely replaces a resource at a known URI No Yes 200 OK or 204 No Content
PATCH Partially modifies a resource No Not guaranteed 200 OK or 204 No Content
DELETE Requests removal of a resource No Yes 204 No Content or 202 Accepted
HEAD Retrieves the same metadata as GET, without a response body Yes Yes 200 OK
OPTIONS Describes communication options, such as supported methods; also used for CORS preflight Yes Yes 200 OK or 204 No Content

“Safe” means the method is intended not to modify server state. “Idempotent” means repeating the request has the same intended effect on server state as executing it once, although the responses may differ. Therefore, GET, PUT, and DELETE are idempotent; POST is not, and PATCH is idempotent only when its defined semantics make it so.

CONNECT and TRACE also exist in HTTP, but they are not ordinary resource-oriented REST methods. CONNECT establishes a network tunnel, while TRACE performs a diagnostic loopback and is commonly disabled for security reasons.

Resource-Oriented Usage

REST APIs model the domain as resources, usually represented by plural nouns and identifiers:

  • GET /orders retrieves a collection of orders.

  • GET /orders/ord_123 retrieves one order.

  • POST /orders creates an order or submits an order-processing operation.

  • PUT /orders/ord_123 replaces the order representation.

  • PATCH /orders/ord_123 changes selected fields.

  • DELETE /orders/ord_123 requests removal of the order.

This avoids RPC-style paths such as /createOrder or /getOrderById, which hide the underlying resources and make caching, evolution, and documentation less consistent.

Request and Response Patterns

  • Create: POST /orders with body {"productId":"prod_42","quantity":2} can return 201 Created, a Location header such as /orders/ord_123, and body {"id":"ord_123","status":"created"}.

  • Read: GET /orders/ord_123 can return 200 OK with body {"id":"ord_123","status":"created","total":49.95}.

  • Partial update: PATCH /orders/ord_123 with body {"status":"shipped"} can return 200 OK with the updated representation.

  • Delete: DELETE /orders/ord_123 can return 204 No Content; asynchronous deletion can instead return 202 Accepted.

  • Accepted processing: POST /orders with body {"productId":"prod_42","quantity":2} can return 202 Accepted with a status-resource URI when completion is deferred.

Choosing the Right Method

  • GET: Simple and naturally cacheable, but cached responses can become stale unless cache control and invalidation are handled correctly. Do not use POST for ordinary retrieval because GET provides safer caching and retry behavior.

  • POST: Flexible for creation and non-CRUD processing, but retries can create duplicates. Use an Idempotency-Key when duplicate submission is harmful.

  • PUT: Predictable and idempotent, but the client normally supplies the complete intended representation. Do not use PUT for an incidental partial change.

  • PATCH: Saves bandwidth and expresses targeted changes, but merge behavior can be ambiguous. Use PUT instead when deterministic whole-replacement semantics are required.

  • DELETE: Gives a clear resource-oriented removal operation, but deletion may need to be asynchronous or represented by a tombstone when regulatory retention rules apply.

Status Codes, Errors, and Common Pitfalls

Use precise status codes instead of returning 200 OK for every outcome:

  • 201 Created for successful resource creation, usually with a Location header.

  • 202 Accepted when processing has started but is not complete.

  • 204 No Content for a successful operation without a response body.

  • 400 Bad Request for malformed syntax or invalid parameters.

  • 401 Unauthorized when authentication is missing or invalid.

  • 403 Forbidden when the caller is authenticated but not authorized.

  • 409 Conflict when the request conflicts with the resource’s current state.

  • 422 Unprocessable Content for syntactically valid JSON that fails business validation.

  • 429 Too Many Requests when the caller exceeds a rate limit.

Error responses should use a consistent format, such as application/problem+json, containing a stable error type, status, title, detail, and optional machine-readable validation errors.

A common mistake is treating POST as automatically safe to retry or treating PATCH as inherently idempotent. The server must implement retry handling explicitly, especially for payments, order creation, and other operations where repeating a request has business consequences.

7

How should an API be versioned?

API versioning is the practice of publishing distinguishable API contracts so existing clients can continue working while an incompatible change is introduced. For public REST APIs, a major version in the URI—such as /v1/orders—is usually the clearest starting point, while compatible additions remain within the same version.

Read full answer

Applies toall HTTP API versions

Versioning Strategies

Strategy Example Advantages Trade-offs
URI path GET /v1/orders Visible, easy to test, naturally cacheable Every major version creates a separate resource tree
Custom header Accept: application/vnd.acme.orders.v1+json Keeps URIs stable and supports content negotiation More complex for clients, gateways, and monitoring
Query parameter GET /orders?version=1 Simple to implement Can interfere with caching and is easy for clients to omit
Contract evolution Add optional fields without changing /v1/orders Avoids unnecessary versions Requires compatibility rules and tolerant clients

For most public REST APIs, prefer /v1/ for major incompatible versions. Header-based media-type versioning is useful when URI structure must remain stable, but it should not be introduced merely to avoid a version segment.

Do not create a new major version for backward-compatible changes. A version scheme may also be unnecessary for a small private API that can guarantee compatible evolution or maintain one stable contract.

Compatibility Rules

Change the major version when a change breaks an existing valid client, including:

  • Removing or renaming a field.

  • Changing a field’s type, format, units, or meaning.

  • Making an optional request field mandatory.

  • Tightening validation so previously valid requests fail.

  • Adding a response field that existing clients must understand.

  • Changing status-code or error semantics.

  • Changing authentication or authorization behavior.

  • Changing method semantics: PUT and DELETE are idempotent, POST is not, and PATCH is not guaranteed to be.

Additive response fields are generally compatible only if clients ignore unknown fields. Adding enum values is potentially breaking because clients may use exhaustive switches; it is safe only when clients have an explicit unknown-value fallback. New optional request fields and endpoints are usually compatible.

Use major versions such as v1 and v2; avoid publishing v1.1 for every release. Put fine-grained release information in a changelog.

Lifecycle and Migration

A versioning strategy must include how old versions are retired:

  1. Publish the new contract and documentation.

  2. Migrate server behavior and data carefully.

  3. Measure usage of each version and identify active clients.

  4. Announce deprecation through documentation, email, and dashboard notifications.

  5. Provide a migration period and support old and new versions concurrently.

  6. Remove the old version only after usage has fallen to an agreed threshold.

Use Deprecation and Sunset response headers where supported, but do not rely on headers alone. API clients may not inspect them, so direct communication and usage telemetry are also necessary.

RFC 8594 defines Deprecation as a Structured Fields Date represented by @ followed by Unix seconds, such as @1775000000. Sunset is an HTTP-date; for example, Thu, 31 Dec 2026 23:59:59 GMT is valid because its weekday and date agree.

Contract Example

For example, POST /v1/orders with JSON body {"customerId":"cus_123","items":[{"sku":"sku_456","quantity":2}]} should return 201 Created, a Location header of /v1/orders/ord_789, and a JSON body such as {"id":"ord_789","status":"pending"}.

The versioned error contract should remain consistent: use 400 Bad Request for malformed input, 422 Unprocessable Content for semantically invalid input when that distinction is supported, 401 Unauthorized for missing or invalid authentication, 403 Forbidden for insufficient authorization, 409 Conflict for state conflicts, and 429 Too Many Requests for rate limiting. Error responses should use a documented format such as application/problem+json.

Best Practices and Pitfalls

  • Separate contract versions from implementation versions: A deployment or database migration should not automatically create a new public API version.

  • Keep versions coarse: Version major incompatible contracts, not every feature release.

  • Design for backward compatibility: Prefer additive changes and expand-contract database migrations before removing old fields.

  • Document everything: Include schemas, error formats, authorization scopes, limits, and migration examples for every version.

  • Measure adoption: Track requests, clients, and error rates per version; otherwise obsolete versions remain unnoticed.

  • Budget for parallel versions: Supporting multiple contracts increases testing, monitoring, documentation, and operational complexity.

  • Avoid disguised breakage: Renaming fields, tightening validation, or changing status-code semantics can break consumers even when the path remains unchanged.

The common interview mistake is treating versioning as only adding /v2. Interviewers usually want to hear about compatibility boundaries, deprecation policy, client migration, and the operational cost of maintaining multiple versions.

8

What is idempotence in API design, and why is it important?

Idempotence means that performing the same API request multiple times has the same intended effect on server state as performing it once. It is essential for safe retries when a client cannot tell whether a request failed before or after the server processed it.

Read full answer

Applies toHTTP/1.1, HTTP/2, and HTTP/3

Core Semantics

Idempotence concerns server state, not necessarily the response. Repeated requests can return different status codes or response bodies while leaving the resource in the same final state.

HTTP method Idempotent? Typical behavior
GET Yes Reads a resource without intentionally modifying it; it is also safe
HEAD Yes Retrieves headers without modifying the resource; it is also safe
PUT Yes Replaces a resource with a known representation
DELETE Yes Ensures a resource does not exist, even if already deleted
POST No Not inherently idempotent; repeated executions can create duplicates or repeat an action
PATCH Not guaranteed An absolute assignment may be idempotent, while a relative modification is not

For example, DELETE /orders/123 might return 204 the first time and 404 afterward. Both requests have the same intended effect: order 123 is absent.

Why It Matters

Network failures create ambiguity. A client sends a request, the server commits it, but the response is lost. The client cannot distinguish this situation from a request that never reached the server, so it retries.

Consider POST /payments with an Idempotency-Key header and a JSON body containing {"order_id":"order-123","amount":4999,"currency":"USD"}. A successful first execution can return 201 Created with a body such as {"payment_id":"pay_789","status":"pending"}.

Without idempotence, a retry may create a second payment and charge the customer twice. With an idempotent design, both executions leave exactly one payment and produce the same payment outcome.

Idempotence is especially important for:

  • Payments, orders, reservations, and refunds

  • Mobile clients on unreliable networks

  • Service-to-service calls with automatic retries

  • Message consumers that may receive the same event more than once

  • Any operation where duplicate execution is expensive or difficult to reverse

Designing Idempotent APIs

Some operations are naturally idempotent:

  • PUT /orders/order-123 replaces the order with the supplied representation.

  • DELETE /orders/order-123 ensures the order does not exist.

  • PUT /inventory/sku-456 sets inventory to an absolute quantity such as 25.

  • PATCH /inventory/sku-456 with {"quantity": 25} is idempotent when the patch assigns an absolute quantity.

Operations that add, increment, decrement, or otherwise depend on the previous value are not naturally idempotent. For example, PATCH /inventory/sku-456 with {"adjustment": -1} means “decrease stock by one.” Applying it twice reduces stock by two units, so it is not idempotent.

For such operations, use an idempotency key. A typical POST design works as follows:

  1. The client generates a unique key, such as a UUID, and sends it in the Idempotency-Key header.

  2. The server scopes the key to the authenticated client and operation.

  3. The server atomically stores the request fingerprint and resulting response.

  4. A repeated request with the same key and payload replays the original result.

  5. The same key with a different payload returns 409 Conflict.

  6. The server retains the key for a defined period covering the client’s retry window.

The response replayed for a retry should normally include the original status code and body so both executions remain indistinguishable to the client. Reusing the key for a different amount should return 409 Conflict, because silently accepting it would hide a client bug.

Trade-offs and Pitfalls

  • Natural idempotence: Usually inexpensive and reliable, but the operation and any side effects must use absolute state transitions such as “set to 25,” not relative ones such as “add 1.”

  • Idempotency keys: Require persistent state, atomic handling of concurrent duplicates, payload comparison, retention policies, and key-scope rules.

  • At-least-once delivery: Kafka or another message broker may redeliver a message, so consumers still need deduplication or idempotent processing.

  • PATCH: Do not assume repeated partial updates are safe. Document exactly which patch formats are idempotent.

  • Authentication scope: Scope keys to the tenant, client, and endpoint so one client cannot replay another client’s operation.

  • Storage retention: Keeping records forever wastes storage; deleting them too early may allow late retries to duplicate an operation.

The common interview mistake is calling every POST safe to retry. The stronger answer is that retries are safe only when the API’s semantics are idempotent, whether through the HTTP method, the operation’s design, or an idempotency-key mechanism.

9

What is API rate limiting and why is it used?

API rate limiting controls how many requests a client, tenant, account, or IP address may send during a specified period. It protects APIs from abuse, prevents accidental traffic spikes, and distributes capacity fairly among consumers.

Read full answer

Applies toHTTP APIs (all versions)

Problem It Solves

Without rate limiting, a single buggy or malicious client could:

  • Exhaust database connections, CPU, memory, or third-party API quotas.

  • Make the API slow or unavailable to legitimate clients.

  • Trigger excessive costs from paid services such as payment or messaging providers.

  • Perform brute-force attacks, credential stuffing, or data scraping.

  • Create unfair traffic spikes by consuming all available capacity.

Rate limiting is primarily a protection and fairness mechanism. It is related to throttling, but throttling may also intentionally slow traffic using queues rather than reject requests.

Common Limiting Strategies

Strategy Behavior Advantages Limitations
Fixed window Allows a quota for each interval, such as 1,000 requests per minute Simple and inexpensive Allows up to 2,000 requests around a window boundary
Sliding window Evaluates requests over the recent time period Smoother enforcement Requires more state or calculations
Token bucket Tokens refill continuously; each request consumes a token Supports controlled bursts while enforcing an average rate Requires shared bucket state
Leaky bucket Processes requests at a steady rate Smooths output to downstream services May add latency or reject excess traffic

A token bucket is often a practical choice for public APIs because it separates the sustained rate from the permitted burst size.

HTTP Request and Response Example

Suppose a reporting API allows each organization to make 100 requests per minute:

Part Example
Request GET /v1/reports/revenue HTTP/1.1 with Host: api.example.com and Authorization: Bearer example-token
Response status 429 Too Many Requests
Response headers Content-Type: application/problem+json; Retry-After: 12; RateLimit-Limit: 100; RateLimit-Remaining: 0; RateLimit-Reset: 12
JSON body { "type": "https://api.example.com/problems/rate-limit-exceeded", "title": "Rate limit exceeded", "status": 429, "detail": "The organization has exhausted its request quota.", "instance": "/v1/reports/revenue" }

429 means the request was rejected because of the client’s request rate. A server experiencing general overload may instead return 503 Service Unavailable. Rate-limit response headers such as RateLimit-Limit, RateLimit-Remaining, and RateLimit-Reset help clients pace themselves without repeatedly failing.

Scope and Trade-offs

Limits should usually be applied using multiple identifiers:

  • API key or OAuth client: Protects one registered application.

  • Tenant or user: Prevents one customer from affecting others.

  • IP address: Helps limit anonymous traffic, but should not be the only control because many users may share an IP.

  • Route or operation: An expensive report may consume more capacity than a simple lookup.

Expensive operations can use a weighted cost: a report might consume 10 tokens while a health check consumes one. Separate limits may also be needed for read and write operations.

Rate limiting adds storage, computation, and coordination overhead. In a distributed API, counters must be shared across instances, introducing consistency and network costs. Organizations also risk rejecting legitimate traffic when limits are poorly chosen.

Best Practices and Failure Handling

  • Choose limits using measured capacity, client traffic patterns, and service cost rather than arbitrary numbers.

  • Return 429 with Retry-After when possible, and include consistent application/problem+json errors.

  • Monitor limit usage, rejected requests, and which clients or routes trigger rejection.

  • Use a separate concurrency limit for long-running operations; request-per-second limits do not prevent many simultaneous connections.

  • When the rate-limit store is unavailable, decide deliberately whether to fail open or fail closed. Failing open favors availability, while failing closed protects downstream capacity.

  • Clients should retry only when appropriate, using exponential backoff with jitter and respecting Retry-After.

  • GET, HEAD, PUT, and DELETE are idempotent; POST is not, and PATCH is not guaranteed to be. Do not immediately retry a non-idempotent POST or PATCH unless an idempotency key makes the retry safe.

A common interview mistake is describing only a fixed per-second counter. Stronger answers cover burst behavior, distributed coordination, HTTP semantics, and what happens when the limiter itself fails.

10

What is OAuth's role in API security?

OAuth 2.0 is an authorization framework that lets clients obtain scoped access to protected APIs without receiving the user’s credentials. It separates the authorization server, which issues tokens, from the resource server, which validates those tokens; OAuth itself is not an authentication protocol.

Read full answer

Applies toOAuth 2.0, OAuth 2.0 Security Best Current Practice (RFC 9700), and OpenID Connect Core 1.0

How OAuth 2.0 Works

OAuth addresses the problem of giving one application limited access to another application’s resources. For example, a reporting service may read a user’s invoices without being able to change their profile.

The main components are:

  • Resource owner: The user who controls the protected resource.

  • Client: The application requesting access, such as a web or mobile application.

  • Authorization server: Authenticates the user, obtains consent, and issues access and refresh tokens.

  • Resource server: The API that protects an endpoint and validates access tokens.

A typical authorization-code flow is:

  1. The client redirects the user to the authorization server.

  2. The authorization server authenticates the user and asks for consent.

  3. It returns an authorization code to the client’s registered redirect URI.

  4. The client sends that code, its code_verifier, and any required client authentication to the token endpoint.

  5. The client sends the access token to the API.

  6. The API validates the token and checks its scopes, audience, expiry, and applicable revocation status.

Authorization code flow is preferred over older implicit grant and Resource Owner Password Credentials flows. Public clients should use PKCE with the S256 method; confidential clients should use PKCE as well.

Tokens, Scopes, and Identity

An access token represents a limited permission grant. APIs validate it locally, usually by checking a cryptographic signature, or through an introspection endpoint.

  • Bearer token: Anyone who obtains it can use it, so it must be transmitted over TLS and protected in storage.

  • Scoped access: A token might allow orders:read but not orders:write.

  • Short expiry: Access tokens are commonly valid for minutes rather than hours, limiting the impact of token theft.

  • Refresh token: Used to obtain new access tokens without repeatedly asking for consent. Refresh tokens should be rotated, and reuse detection should invalidate the affected token family.

  • Audience restriction: A token intended for the invoices API should not be accepted by an unrelated API.

JWT access tokens can be validated locally, reducing network latency and authorization-server dependencies. Immediate revocation is harder because a self-contained JWT remains usable until it expires unless another revocation mechanism is added. Opaque tokens support immediate revocation but require an introspection call.

OAuth does not provide user authentication by itself. When the client also needs to establish the user’s identity, OpenID Connect provides an ID token and a /userinfo endpoint.

API Example

A client using the client-credentials grant can send a form-encoded POST request to the authorization server’s token endpoint, such as POST https://identity.example.com/oauth2/token. It includes grant_type=client_credentials, the requested scope encoded as orders%3Aread, and client authentication appropriate to the deployment. A successful response has status 200 OK, content type application/json, and a body containing an access_token, token_type set to Bearer, an expires_in such as 900, and the granted scope.

The client then sends GET https://api.example.com/v1/orders with an Authorization: Bearer <access-token> header and Accept: application/json. A valid request can return 200 OK with a JSON body such as {"data":[{"id":"ord_123","status":"shipped"}]}.

A missing or invalid token produces 401 Unauthorized, normally with a WWW-Authenticate: Bearer header and a problem-details JSON body identifying the authentication failure. A valid token with insufficient permissions generally produces 403 Forbidden with the insufficient_scope error code. These endpoint paths and response representations are deployment conventions rather than universal OAuth requirements.

Security Practices

  • Require TLS 1.2 or newer, preferably TLS 1.3, and never send tokens in URLs or logs.

  • Validate the signature or introspection result, issuer, audience, expiry, scope, and token type. Do not decode a JWT without validating it.

  • Register exact redirect URIs and prevent open redirects.

  • Store tokens securely. Browser clients should avoid exposing refresh tokens to JavaScript where possible.

  • Use rate limits, token revocation, audit logs, and monitoring for unusual token use.

  • Rotate refresh tokens, invalidate the affected token family when reuse is detected, and require reauthentication for sensitive operations.

  • Treat client secrets as credentials; public mobile and browser clients cannot keep a secret confidential.

Trade-offs and Alternatives

OAuth adds authorization-server traffic, token management, consent screens, and operational complexity. Local JWT validation reduces latency but sacrifices immediate revocation; introspection improves revocation control but adds a network dependency and roughly one authorization-server round trip.

Use OAuth when applications need delegated access or centralized, scoped authorization. For simple first-party service-to-service communication, workload identity with mutually authenticated TLS may be simpler. API keys can fit low-risk integrations, but OAuth 2.0 client credentials generally provides better lifecycle management, scoping, and revocation.

Interviewers commonly look for whether you can explain the authorization-code flow with PKCE, distinguish OAuth from OpenID Connect, and avoid the common mistake of treating an access token as proof of identity without validating its audience and permissions.

11

How do you maintain backward compatibility in an API?

Backward compatibility means existing clients can continue working after an API evolves without requiring immediate client changes. The safest approach is to make compatible changes by default, version only genuinely breaking changes, and verify compatibility through contracts, tests, and production telemetry.

Read full answer

Applies toHTTP APIs using HTTP/1.1, HTTP/2, or HTTP/3 semantics

Compatibility Contract

Backward compatibility has two dimensions:

  • Backward compatibility: New servers continue supporting old clients.

  • Forward compatibility: New clients continue working with old servers, often by ignoring unsupported response fields and using sensible defaults.

Treat the API contract—not just its implementation—as the compatibility boundary. Important elements include:

  • URLs, methods, headers, parameters, and status-code semantics

  • Request and response schemas

  • Field names, types, units, formats, and nullability

  • Validation rules

  • Authentication and authorization behavior

  • Pagination, filtering, sorting, and error formats

  • Business semantics behind fields and state transitions

A change can be technically schema-compatible but still break clients. For example, changing amount from cents to dollars preserves its type but changes its meaning.

Making Compatible Changes

Prefer changes that existing clients can safely ignore or understand.

Change Compatibility impact
Add an optional request field Compatible for old clients if the server defines a safe default; forward-compatible only if old servers ignore it
Add a response field Usually compatible if clients tolerate unknown fields
Add a new endpoint Compatible
Add a new enum value Potentially breaking if clients reject unknown values
Make an optional field required Breaking
Change a field’s type or meaning Breaking
Tighten validation Breaking if previously valid requests are rejected
Change a status code or error shape Potentially breaking
Change default pagination or sorting Potentially breaking

For a new optional request field, define what the new server does when an old client omits it. If new clients may call old servers, old servers must ignore the unknown field rather than reject it.

Avoid renaming or repurposing fields. If a schema change is unavoidable, introduce a new field or resource, migrate consumers, and remove the old representation only after its usage has fallen to an acceptable level.

Preserve HTTP method semantics: PUT and DELETE are idempotent, POST is not, and PATCH is not guaranteed to be idempotent. An idempotency mechanism can make a particular create operation safe to retry without changing POST semantics.

Versioning Breaking Changes

Use versioning only when additive or tolerant changes are insufficient. Common approaches include:

  • URI versioning: /v1/orders and /v2/orders; simple to inspect but versioning becomes coarse-grained.

  • Header or content negotiation: The client requests a contract version through a custom header or a media-type parameter in Accept; cleaner URLs but requires routing and client discipline.

  • Endpoint-specific versions: Only the affected endpoint changes; reduces blast radius but can make the overall API fragmented.

Versioning costs more than adding fields: clients must migrate, documentation and tests multiply, and the organization may operate multiple contracts for months. It also encourages clients to remain on old versions indefinitely. Prefer contract evolution over versions, and define a published compatibility policy and deprecation window.

When deprecating an endpoint, announce deprecation with the Deprecation header and expected removal timing with the Sunset header, which contains an HTTP-date. Provide migration documentation, monitor remaining consumers, and avoid removing the version until usage justifies it.

Verifying Compatibility

Use automated checks at several levels:

  • Schema validation: Validate examples and generated clients against the contract.

  • Consumer-driven contract tests: Verify that the provider still satisfies clients’ expectations.

  • Backward-compatibility testing: Run old request fixtures against the new implementation.

  • Golden tests: Compare stable response fields and semantics, excluding explicitly unstable fields.

  • Canary or staged rollout: Release the new server to a small traffic percentage before broad deployment.

  • Production telemetry: Track endpoint versions, headers, client identifiers, and error patterns by consumer.

Maintain a registry of active clients and contracts. Without consumer visibility, an apparently compatible server change can still break an unknown integration.

Code Example

A compatible response can add an optional field without changing existing fields:

POST /v1/orders HTTP/1.1
Host: api.example.com
Content-Type: application/json
Idempotency-Key: order-7f21

{"sku":"A-123","quantity":2}
HTTP/1.1 201 Created
Content-Type: application/json
Location: /v1/orders/order-42

{
  "id": "order-42",
  "status": "pending",
  "total": 2500,
  "currency": "USD",
  "estimated_delivery_date": "2026-07-10"
}

Clients with strict schema deserializers may still reject the new response field, so response evolution must be coordinated with known client behavior.

Best Practices and Trade-offs

  • Document compatibility guarantees and publish a change history.

  • Treat unexpected input rejection as a breaking change.

  • Keep error responses consistent, preferably using a documented format such as application/problem+json.

  • Do not change units, timestamp formats, identifiers, or pagination semantics without migration guidance.

  • Use idempotency keys for retried create operations; compatibility does not make non-idempotent POST requests safe to repeat.

  • Establish measurable deprecation criteria rather than removing endpoints based only on calendar dates.

  • Do not use versioning as a substitute for good API design.

  • Test failure modes, not only successful responses; changed error codes and malformed validation errors are common hidden breaks.

Interviewers typically look for a change-classification policy, consumer contract testing, and a deliberate versioning and deprecation strategy. The common mistake is declaring every change backward-compatible without considering strict client parsers, altered validation rules, or changed business semantics.

12

What do common HTTP API status codes mean?

An HTTP status code is a three-digit result returned by an API to indicate whether a request succeeded and, if not, whether the problem belongs to the client or server. Correct status codes make an API predictable to clients, gateways, monitoring systems, and SDKs.

Read full answer

Applies toHTTP/1.1, HTTP/2, and HTTP/3; RFC 9110 status-code semantics, RFC 6585 for `429 Too Many Requests`, and RFC 9457 Problem Details

Status Code Families

Range Class General meaning
1xx Informational Request received; the final response is still coming.
2xx Success Request successfully received, understood, and accepted; processing may still be pending for 202.
3xx Redirection Further action is needed, such as following a Location or using a cached response.
4xx Client error The server cannot fulfill the request because of a client-side condition.
5xx Server error The server cannot fulfill the request because of a server-side condition.

The 4xx versus 5xx distinction matters: 400 indicates that the client must change its request, while 500 indicates an unexpected server failure.

Common Codes and Meanings

Code Meaning Typical use
200 OK Request succeeded A read or update returned a response body.
201 Created Resource was created Return the new representation and, where appropriate, a Location header.
202 Accepted Work was accepted for processing An asynchronous operation has not necessarily completed.
204 No Content Successful with no body Common after a successful DELETE.
304 Not Modified Cached representation is valid Used with conditional requests such as If-None-Match.
400 Bad Request Malformed or invalid request Invalid JSON, malformed syntax, or missing required information.
401 Unauthorized Authentication is missing or invalid Despite its name, it primarily means the caller is unauthenticated.
403 Forbidden Caller lacks permission The server refuses access even though the caller may be authenticated.
404 Not Found Resource not found The requested resource does not exist or must be treated as nonexistent.
405 Method Not Allowed Method is unsupported Include an Allow header listing supported methods.
409 Conflict Request conflicts with current state Duplicate creation, version conflict, or concurrent-update conflict.
422 Unprocessable Content Syntactically valid content fails validation For example, a valid JSON field contains an invalid value.
429 Too Many Requests Rate limit exceeded Include Retry-After when the server can estimate the retry time.
500 Internal Server Error Unexpected server failure An unhandled exception or other unexpected internal condition.
502 Bad Gateway Invalid response from an upstream service Commonly emitted by a gateway or reverse proxy.
503 Service Unavailable Service is temporarily unavailable Maintenance, overload, or an unavailable dependency.
504 Gateway Timeout Upstream service did not respond in time Usually paired with a server-side timeout.

Designing Error Responses

A status code should be accompanied by a machine-readable body. RFC 9457 defines application/problem+json with members such as type, title, status, detail, and instance.

Useful error responses should:

  • Identify what failed, ideally through a stable error code or problem type.

  • Explain the problem in human-readable language.

  • Identify an invalid field without exposing stack traces or secrets.

  • Preserve a traceId or request identifier for support and debugging.

  • Use a predictable schema across error categories.

A 401 response must include a WWW-Authenticate header. A 403 response does not require that challenge because the caller may already be authenticated successfully.

Standard status codes improve interoperability among generic clients, gateways, monitoring, and retry policies, but they are intentionally coarse. Problem Details adds machine-readable context without inventing nonstandard status codes; custom numeric codes usually reduce interoperability and should be avoided.

For example, POST /orders with body {"customerId":"cust_123","items":[{"sku":"book-001","quantity":0}]} can return 422 Unprocessable Content with an application/problem+json body. A successful creation returns 201 Created, a Location: /orders/order_456 header, and a body such as {"id":"order_456","status":"pending"}.

Practical API Design Rules

  • Use POST for non-idempotent operations and provide an idempotency key where duplicate processing would be harmful. POST is not guaranteed to be idempotent; PUT and DELETE are idempotent, while PATCH is not guaranteed to be.

  • Use 201 when a resource is created and 202 when processing is asynchronous; provide a status or result URL where useful.

  • Prefer 400 for malformed requests and 422 for syntactically valid requests that fail semantic validation.

  • Use 409 when the client must resolve a conflict with the resource’s current state.

  • Use 503 for temporary service unavailability and 504 for a timeout involving an upstream service.

  • Keep 5xx responses generic to clients and log full internal exceptions server-side.

Common Mistakes

  • Returning 200 OK for every result forces clients to inspect the body instead of using standard semantics.

  • Returning 500 for invalid client input misleads clients, dashboards, and retry policies.

  • Sending a response body with 204 No Content violates the status’s semantics.

  • Exposing stack traces, database errors, or dependency names creates an information-disclosure risk.

  • Treating every 5xx as retryable can amplify an outage. Use bounded exponential backoff with jitter and respect guidance such as 429 Retry-After or 503 Retry-After.

13

How do you design REST APIs that clients can use easily?

A consumable API provides a predictable contract: consistent resource naming, HTTP semantics, structured responses, discoverable documentation, and clear failure behavior. Clients should be able to integrate without relying on undocumented implementation details.

Read full answer

Applies toREST over HTTP/1.1, HTTP/2, and HTTP/3

Start With a Stable Contract

Before choosing endpoints, identify the API’s consumers and define:

  • Resources: Model business concepts such as orders and customers, not implementation details such as database tables.

  • Operations: Express intended actions through HTTP methods rather than verbs embedded in URLs.

  • Data model: Define field names, types, required fields, nullability, enumerations, and backward-compatibility rules.

  • Contract: Publish an OpenAPI specification and examples, but test that runtime behavior remains synchronized with it.

  • Ownership: Give each API a clear owning team, support channel, and deprecation process.

Clients value predictability more than theoretical REST purity. A slightly less elegant but consistent contract is usually easier to consume than one that exposes implementation details.

Resource and HTTP Semantics

Use plural nouns and hierarchy sparingly:

GET    /orders/{orderId}
POST   /orders
PATCH  /orders/{orderId}
DELETE /orders/{orderId}
Method Safe Idempotent Typical use
GET Yes Yes Retrieve a resource or collection
HEAD Yes Yes Retrieve response metadata
POST No No Create or invoke a non-idempotent operation
PUT No Yes Replace a resource completely
PATCH No Not guaranteed Apply a partial update
DELETE No Yes Remove a resource
OPTIONS Yes Yes Discover supported methods

Idempotency means repeating the same request produces the same intended server state, even if the response differs. For example, repeated DELETE requests may return 204 and then 404, but the resource remains deleted.

Prefer PUT for full replacement and PATCH for partial updates. However, define patch semantics precisely: JSON Merge Patch, JSON Patch, and custom field-mask formats have different behavior and error cases.

Responses, Errors, and Data Shape

Use correct status codes:

  • 200 for a successful response with a body.

  • 201 for creation, usually with a Location header.

  • 204 for success with no response body.

  • 400 for malformed syntax or invalid parameters.

  • 401 when authentication is missing or invalid.

  • 403 when an authenticated principal lacks authorization.

  • 404 when the resource is unavailable or hidden by authorization rules.

  • 409 for state conflicts, such as duplicate operations.

  • 422 for syntactically valid requests that fail semantic validation.

  • 429 for rate limiting, ideally with Retry-After.

Use a consistent error envelope such as application/problem+json. A machine-readable error code is often more useful to clients than parsing a human-readable message.

Keep response conventions stable:

  • Use opaque IDs; clients should not parse their structure.

  • Use ISO 8601 timestamps in UTC.

  • Represent money as a decimal string or integer minor units, never a floating-point number.

  • Distinguish explicitly between a missing field and a field whose value is null.

  • Avoid exposing stack traces, database errors, or internal service names.

Pagination, Filtering, Versioning, and Security

Pagination Advantages Limitations
Offset Easy links, allows arbitrary page jumps Performance degrades on large datasets; inserts can cause duplicates or omissions
Cursor Stable and efficient for large or changing collections Opaque and generally not human-readable

Provide limit and an opaque cursor for large collections. Return enough metadata for clients to navigate, and avoid promising that results are globally consistent across pages.

For filtering and sorting:

  • Allow-list supported query parameters and sort fields rather than accepting arbitrary database expressions.

  • Define malformed parameter behavior, such as returning 400, and semantic validation failures as 422.

  • Support only the filters clients need; broad filtering increases indexing, query-planning, and abuse-prevention costs.

  • Use deterministic ordering, including a tie-breaker when clients sort by a non-unique field.

For versioning:

  • Prefer backward-compatible, additive changes and version only when a breaking change is unavoidable.

  • Path versioning such as /v1/orders and /v2/orders is easy to route and debug but can multiply operational work.

  • Header or media-type versioning keeps URLs cleaner but is less visible to proxies, gateways, and some clients.

  • Run old and new versions for a documented migration period, publish migration guidance, measure remaining usage, and establish a deprecation date.

For security:

  • Use OAuth 2.0 access tokens for user-delegated access and API keys for server-to-server identification.

  • For signed JWT access tokens, validate the signature and algorithm, issuer, audience, expiry, and scopes. For opaque tokens, validate them through authorization-server introspection or a trusted gateway.

  • Keep authentication separate from authorization.

  • Never place credentials in query parameters.

  • Prefer 401 for invalid credentials and 403 for insufficient permissions.

Rate-limit expensive endpoints and return 429 with retry guidance. For unsafe operations, support an Idempotency-Key header and persist the result so a retried request does not create duplicate payments or orders.

For webhooks, sign payloads, include unique event IDs, retry with backoff, and document delivery as at least once. Consumers must therefore support deduplication.

Code Example

A typical creation request:

curl -i https://api.example.com/orders \
  -X POST \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: order-7f31c0" \
  -d '{"customerId":"cus_123","items":[{"sku":"sku_456","quantity":2}]}'

Successful response:

HTTP/1.1 201 Created
Location: /orders/ord_789
Content-Type: application/json
{
  "id": "ord_789",
  "status": "pending",
  "customerId": "cus_123",
  "createdAt": "2025-02-10T14:30:00Z"
}

A consistent validation error:

HTTP/1.1 422 Unprocessable Content
Content-Type: application/problem+json
{
  "type": "https://api.example.com/problems/validation-error",
  "title": "Request validation failed",
  "status": 422,
  "detail": "At least one order item is required.",
  "instance": "/orders"
}

Trade-offs and Interview Checklist

Strict contracts, idempotency storage, cursor pagination, filtering, rate limits, and versioning all add implementation and operational cost. Avoid unnecessary complexity for internal APIs with coordinated clients, but design public or cross-team APIs for predictable failure behavior and gradual evolution.

Interviewers commonly look for:

  • Correct use of HTTP safety and idempotency.

  • Consistent resource names, status codes, and error bodies.

  • Pagination, filtering, sorting, and validation rather than unbounded lists.

  • Authentication, authorization, rate limiting, and idempotency considered explicitly.

  • A plan for backward-compatible changes, versioning, migration, and deprecation.

A common mistake is designing endpoints around internal tables while ignoring pagination, error contracts, retries, and client versioning. Those details determine whether the API is actually easy to consume.

14

How should an API be documented for end users?

Document an API with both a machine-readable contract and task-oriented guides so consumers can integrate without reading the implementation or contacting support. For REST APIs, the contract should normally be defined in OpenAPI 3.1, while examples and quickstarts explain how to complete common workflows.

Read full answer

Applies toREST APIs using HTTP, with OpenAPI 3.1

Documentation strategy

Start by identifying the audiences and their needs:

Audience Main need Best format
API consumers Exact endpoints, schemas, errors, and authentication OpenAPI reference
First-time users Guidance for common tasks Quickstart and tutorials
Support and operations Error meanings, troubleshooting, and escalation steps Runbook and diagnostic guide
API maintainers Change history and compatibility guarantees Changelog and migration guide

Do not maintain the same information independently in prose and OpenAPI. Define the contract in OpenAPI, validate it in CI, and generate reference documentation from it. Handwritten guides should add context and workflows that a schema cannot express.

Required contract details

The documentation should describe:

  • Resources and operations: Use plural resource names such as /v1/orders, and explain the purpose and business meaning of every operation.

  • HTTP semantics: Document which requests are safe or idempotent. GET, HEAD, PUT, and DELETE are idempotent; POST is not, and PATCH is not guaranteed to be idempotent.

  • Parameters: Define path, query, and header parameters, including validation rules, units, optionality, and defaults.

  • Request and response schemas: Include required fields, formats, nullable values, and realistic examples rather than placeholder values.

  • Status codes: Explain 201 for creation, 204 for an empty successful response, 400 for malformed requests, 422 for semantically invalid input, 401 for missing or invalid authentication, 403 for insufficient authorization, 409 for state conflicts, and 429 for rate limiting.

  • Errors: Use a consistent format such as RFC 9457 application/problem+json, including a stable machine-readable error code.

  • Authentication and authorization: Explain API keys, OAuth 2.0 flows and scopes, token expiry, and the difference between 401 and 403. Never include usable credentials.

  • Pagination and filtering: Document cursor or offset pagination, page-size limits, stable sort criteria, and filtering rules.

  • Rate limits: State quotas, 429 behavior, relevant headers, and recommended backoff. Clients should use exponential backoff with jitter.

  • Reliability semantics: Document timeouts, safe retry conditions, and idempotency keys for retried POST operations.

End-user guidance

Reference documentation is necessary but insufficient. Provide short, task-based examples such as creating an order, retrieving it, handling pagination, or rotating an API key.

A successful authenticated request should show the exact method, path, and headers. For example, a request for GET /v1/orders/ord_123 includes Authorization: Bearer <access-token> and Accept: application/json.

Scenario Status Content type Example body
Retrieve an existing order 200 OK application/json {"id":"ord_123","status":"fulfilled","total":{"amount":42.50,"currency":"USD"}}
Retrieve a missing order 404 Not Found application/problem+json {"type":"https://api.example.com/problems/order-not-found","title":"Order not found","status":404,"detail":"Order ord_123 does not exist.","instance":"/v1/orders/ord_123"}

Also document operational expectations that are often missing:

  • Request and response size limits

  • Processing-time expectations, described as approximate rather than guaranteed

  • Idempotency-key retention

  • Webhook delivery, signatures, retries, ordering, and replay handling

  • Rate-limit behavior

  • API versioning and deprecation policy

  • Changelog entries with examples of required client changes

Avoid documenting internal implementation details that consumers cannot rely on, such as database tables or service topology.

Publishing and maintenance

Treat documentation as part of the API contract. Run OpenAPI linting and contract tests in CI, publish versioned documentation, and require changes to operations, schemas, authentication, or error codes to include corresponding documentation updates.

Use additive changes whenever possible. For breaking changes, publish a new version or provide a migration period, document the differences, and supply before-and-after examples.

Trade-offs and common mistakes

A complete documentation portal improves onboarding and reduces support load, but it adds publishing, review, and synchronization work. Do not create multiple manually maintained sources of truth, because they inevitably drift.

The common interview mistake is publishing only an endpoint list. Interviewers usually look for attention to consumer workflows, error semantics, authentication, pagination, versioning, and the maintenance process. For GraphQL or gRPC, use SDL or Protocol Buffers as the machine-readable contract, while retaining similar task-oriented guides.

15

What factors should guide pagination design for API responses?

Pagination controls how an API returns a large collection in manageable chunks. The right approach depends on result-set size, query cost, data mutation, consistency requirements, client navigation needs, and whether clients need exact totals.

Read full answer

Applies toall REST API versions

Key Considerations

  • Page size: Set a default and maximum to control response size, database work, memory use, and latency. Very small pages increase request overhead; very large pages consume bandwidth and server resources.

  • Ordering: Use a deterministic sort order with a unique tie-breaker such as created_at, id. Without one, records with equal sort values may appear unpredictably or move between pages.

  • Filtering and sorting: Pagination must compose consistently with filters and sort fields. These fields often determine which database indexes are usable.

  • Result consistency: Inserts, deletes, and updates between requests can cause offset pagination to skip or duplicate records. Cursor pagination is less affected by insertions, but mutations to sort keys and deleted records can still affect traversal.

  • Client requirements: A mobile feed usually benefits from sequential cursor access, while an administrative report may need numbered pages and an estimated total.

  • Total count: An exact total can require an expensive count query. Prefer has_more or next_cursor when clients only need to know whether more data exists.

  • Access control: Apply authorization and tenant filters before pagination. Treat cursors as untrusted input and never allow them to bypass record-level permissions.

Offset vs Cursor Pagination

Approach Advantages Limitations Best fit
Offset pagination Simple URLs, visible page numbers, easy jumps Deep offsets get slower; concurrent changes can skip or duplicate rows Small, stable datasets and administrative interfaces
Cursor pagination Efficient sequential access; less sensitive to insertions than offsets No arbitrary page jumps; implementation-specific format; affected by relevant mutations Feeds, logs, exports, and frequently changing collections
Keyset pagination Seeks using the last sort key instead of counting skipped rows Requires stable, indexed ordering; mutations to sort keys affect traversal Large tables with monotonic or stable ordering

Keyset pagination is commonly used to implement cursor pagination. It compares the last returned sort tuple with subsequent rows, so its performance depends heavily on a matching composite index.

HTTP Contract

A request might be GET /orders?limit=50&cursor=<opaque-cursor>. A response could be 200 OK with the body {"data":[{"id":"ord_123","created_at":"2025-03-08T10:15:00Z","status":"paid"}],"page":{"limit":50,"next_cursor":"<opaque-cursor>","has_more":true}}.

The contract should define:

  • Maximum limit: For example, clients may request at most 100 records; larger requests return 400 Bad Request.

  • Invalid cursor: Return 400 Bad Request for a malformed, expired, or otherwise invalid cursor.

  • Parameter naming: Use one documented input name, such as cursor, and one response field, such as next_cursor; avoid aliases such as page, offset, and per_page.

  • Opaque cursors: The contract must require clients to treat the cursor as opaque. A signed cursor prevents tampering; encrypt it only when its contents must remain confidential.

  • Empty results: For a JSON page envelope, return 200 OK with an empty data array. Reserve 204 No Content for a successful response that intentionally has no body.

Choosing and Operating Pagination

For an e-commerce order history, cursor pagination is usually preferable because the dataset grows over time, users rarely jump directly to page 900, and new orders should not shift every later page. Offset pagination remains reasonable for a small, stable table where users need numbered pages.

Also plan for:

  • Index alignment: Match the index to the API’s filters, sort order, and cursor predicate. Otherwise, pagination only distributes a slow query across requests.

  • Deep-page limits: Offset APIs may need a maximum offset or a transition to cursor pagination as the skipped-row count grows.

  • Snapshot semantics: Exact consistency across pages may require a snapshot token or transaction-based session, adding state or operational complexity.

  • Caching: Cache paginated URLs when appropriate, but include every parameter affecting the result and avoid exposing one user’s data to another.

  • Export workflows: For millions of records, use an asynchronous export rather than requiring clients to retrieve thousands of pages.

Interviewers commonly look for whether you can explain these trade-offs. A common mistake is choosing cursors without deterministic ordering, cursor validation, expiration rules, and authorization.

16

What is HATEOAS and how does it guide API design?

HATEOAS—Hypermedia As The Engine Of Application State—is a REST architectural constraint in which responses include hypermedia controls, especially links, that tell clients which resources or state transitions are currently available. It guides API design by moving workflow knowledge from hardcoded client paths into server-provided metadata, reducing coupling while increasing client and protocol complexity.

Read full answer

Applies toall versions of REST APIs; HATEOAS is an architectural constraint, not a versioned HTTP feature

The Problem HATEOAS Solves

Traditional clients often hardcode URLs and business transitions, such as POST /orders/{id}/cancel or GET /orders/{id}/status. If the server changes that workflow, multiple clients may require coordinated updates.

HATEOAS instead advertises the available next steps in the response. For example, a pending order can expose a self link and a cancellation link. The client follows the advertised relation rather than constructing the cancellation URL itself. This reduces hardcoded workflow knowledge, but the server must maintain correct links and clients must handle links appearing, disappearing, or changing.

How Hypermedia Guides API Design

HATEOAS affects several parts of an API:

  • State transitions: A resource advertises only the actions currently available, such as cancellation while an order is pending.

  • Resource relationships: Links connect related resources, supporting workflows such as finding an order’s payment or customer.

  • Navigation: Responses can advertise pagination, search, or collection links.

  • Workflow contracts: Relation types communicate intent without requiring clients to infer behavior from URL paths.

HATEOAS does not eliminate specialized action endpoints. It allows the server to tell clients when those endpoints are relevant and where they are located. For example, /orders/123/cancel may still exist, but the order response only advertises it while cancellation is allowed.

The server guides rather than controls the client: links describe available choices, while the client decides whether and how to follow one. Every target must still be authorized and validated by the server.

Representation Formats

HATEOAS commonly uses:

  • Link headers defined by RFC 8288

  • HAL documents using _links and optionally _embedded

  • JSON:API top-level links and resource relationships

  • Vendor-specific relation formats

A link’s target identifies where to act, while its relation type describes what the link means. Extension relation types should use stable absolute URIs. For example, https://api.example.com/rels/cancel can identify a cancellation transition.

The media type defines the representation format, but it does not by itself define every relation’s business meaning. Important relations still need a documented or registered contract.

Request and Response Example

A client requests GET /orders/123 HTTP/1.1 with Accept: application/hal+json. The server returns 200 OK with Content-Type: application/hal+json and a compact HAL body such as {"id":"123","status":"pending","_links":{"self":{"href":"/orders/123"},"cancel":{"href":"/orders/123/cancel","rel":"https://api.example.com/rels/cancel"}}}.

The client can then send POST /orders/123/cancel HTTP/1.1 with Content-Type: application/json and an Idempotency-Key header. If cancellation is asynchronous, the server can return 202 Accepted with {"status":"cancellation_requested"}.

Because POST is not inherently idempotent, an idempotency key remains useful for safely retrying retryable operations. HATEOAS links also do not replace authorization or concurrency controls; a previously advertised action may now produce 403 or 409.

Trade-offs and When Not to Use It

  • Discoverability: Clients can discover supported actions without duplicating workflow rules.

  • Evolvability: The server can change target URLs or workflows, although clients still need support for new relation semantics.

  • Client complexity: Clients must parse links, select relations, and handle missing transitions.

  • Payload size: Link-rich responses increase bandwidth and parsing work.

  • Security exposure: Links can reveal workflow structure or internal resource identifiers, so they should not disclose unauthorized or sensitive details.

  • Caching: Cacheability still depends on HTTP semantics and headers such as Cache-Control. State- or permission-dependent links may require private, no-store, or a short TTL.

  • Operational effort: The server must generate links consistently and keep them synchronized with authorization and business-state rules.

Do not make HATEOAS the exclusive interaction model for simple CRUD APIs used only by controlled first-party clients when a stable, documented schema is easier to operate. It is also a poor fit when clients cannot parse hypermedia controls or when payload and latency budgets are extremely tight. A hybrid API—stable resource URLs for ordinary CRUD and hypermedia links for state-dependent workflows—is often the practical choice.

Best Practices

  • Use stable, documented relation types rather than paths as the client-facing contract.

  • Advertise only currently authorized and useful transitions.

  • Include self links and pagination links where appropriate.

  • Treat links as discoverability hints, not authorization; enforce permissions when the target is accessed.

  • Version or otherwise manage relation semantics when they change; HATEOAS reduces coupling but does not remove the need for an API evolution policy.

  • Document the expected relation and response behavior so clients can handle absent links safely.

A common interview mistake is describing HATEOAS merely as “returning links.” The stronger explanation is that hypermedia controls let a client drive a server-described state machine without hardcoding every transition, while requiring deliberate relation design, caching, authorization, and compatibility rules.

17

How do you design localized, internationalized APIs?

Internationalization (i18n) means designing an API whose data and behavior work across languages and regions without application-specific branching. Localization (l10n) means adapting human-readable content and presentation for a specific locale.

Read full answer

Applies toHTTP/1.1, HTTP/2, and HTTP/3 (version-independent design)

Design Goals and Canonical Data

The problem i18n solves is that language, formatting, and regional expectations vary, while machine-readable contracts must remain stable. Separate canonical domain data from locale-dependent presentation.

  • Language: Translate user-facing labels, descriptions, notifications, and validation messages.

  • Locale: Use locale conventions for dates, numbers, percentages, addresses, and names, while retaining structured data where clients might otherwise interpret it differently.

  • Time zone: Store and exchange timestamps in UTC, such as 2025-03-08T14:30:00Z; let the client select the display time zone.

  • Currency: Return an ISO 4217 currency code and an integer amount in the currency’s minor unit. Never infer currency from locale alone.

  • Encoding: Accept and return UTF-8 Unicode.

  • Stable identifiers: Keep field names, status values, enum codes, and error codes independent of language.

For example, an e-commerce API should return an amount and currency, not only "€19.99". It should return IN_STOCK rather than localizing the enum to "En stock".

Do not infer jurisdiction, tax rules, currency, or data residency from locale; those are separate business and compliance concerns. Returning canonical values gives clients precision and flexibility, but they must implement locale-aware formatting correctly.

Negotiation and Translation Management

Use Accept-Language to negotiate human-readable representations. Match supported locales using the standard language-range rules, honoring quality weights, excluding languages marked q=0, and handling wildcard ranges according to the documented policy.

  • Prefer an exact supported locale such as fr-CA.

  • Then apply the documented less-specific fallback, such as fr or a configured default such as en-US.

  • Return 406 Not Acceptable when no representation is acceptable, or ignore the preference and return the default only when that contract is explicitly documented.

  • If account preferences and Accept-Language are both supported, define their precedence rather than allowing one to override the other implicitly.

Manage translations separately from canonical domain data:

  • Externalize messages: Keep translatable strings outside business logic.

  • Use stable keys: Use identifiers such as payment.decline.insufficient_funds internally.

  • Preserve placeholders: Protect variables such as {orderId} from translation changes.

  • Handle Unicode safely: Support non-ASCII names, scripts, and emoji without assuming a fixed byte length.

  • Keep errors stable: Return a stable machine-readable code even when the human-readable detail is translated.

Translation management costs storage, review, release coordination, and testing for every locale. If an API serves only machine-to-machine clients, stable codes and canonical numeric values may provide more value than translated content.

Storage, Caching, and Failure Handling

Store canonical records and localized variants according to their different update rates. This separation improves translation workflows but adds joins, synchronization, and operational complexity.

  • Add Vary: Accept-Language to responses whose content or language changes with negotiation, including localized errors.

  • If an intermediary does not honor Vary reliably, include the resolved locale in the application-cache key.

  • Expect lower cache hit rates because each language creates another representation.

  • Keep canonical operations available when a translation provider fails; serve the default language or a stable code rather than failing the whole request.

Code Example

A successful negotiated response contains localized text alongside stable machine-readable fields:

GET /products/42 HTTP/1.1
Host: api.example.com
Accept-Language: fr-CA, fr;q=0.9, en;q=0.8
HTTP/1.1 200 OK
Content-Type: application/json
Content-Language: fr-CA
Vary: Accept-Language

{
  "id": "42",
  "name": "Casque de vélo",
  "price": {
    "amountMinor": 1999,
    "currency": "EUR"
  },
  "availability": "IN_STOCK",
  "availabilityLabel": "En stock",
  "updatedAt": "2025-03-08T14:30:00Z"
}

Localized errors can use Problem Details while retaining a stable error identifier:

HTTP/1.1 422 Unprocessable Content
Content-Type: application/problem+json
Content-Language: fr-CA
Vary: Accept-Language

{
  "type": "https://api.example.com/problems/validation-error",
  "title": "Échec de la validation",
  "status": 422,
  "detail": "La date de livraison doit être au format AAAA-MM-JJ.",
  "code": "INVALID_DELIVERY_DATE",
  "invalidField": "deliveryDate"
}

Best Practices and Common Pitfalls

  • Publish the supported-locale list and deterministic fallback rules.

  • Keep API fields, enum values, and error codes language-independent.

  • Never localize URLs, pagination cursors, timestamps, or opaque identifiers.

  • Test Arabic, Chinese, emoji, right-to-left text, and malformed Unicode.

  • Document how generated SDKs map locale preferences to Accept-Language.

  • Do not translate values used for business rules, analytics, or validation.

  • Avoid a ?lang= parameter when Accept-Language already expresses the requirement; use it only when the language identifies resource data rather than a negotiated representation.

Interviewers commonly look for separation of canonical data from presentation, deterministic fallback rules, cache fragmentation, and graceful degradation when translations are unavailable.

18

What are best practices for API error response design?

A good API error response should be consistent, machine-readable, specific, and safe. Use a documented error format such as RFC 9457 Problem Details, return an appropriate HTTP status code, and provide a stable error code that clients can handle without parsing human-readable text.

Read full answer

Applies toHTTP APIs across all versions

Why Error Responses Matter

Errors are part of the API contract, not an implementation detail. Clients need to distinguish invalid input from authentication failure, a temporary outage, or a retryable conflict so they can decide whether to correct the request, refresh credentials, or retry.

A useful error response should let a caller:

  • Identify the failure using an HTTP status code and stable machine-readable code.

  • Understand what failed through a concise, human-readable message.

  • Locate the problem using field-level validation details or a request identifier.

  • Determine whether retrying is appropriate.

  • Correlate the failure with server logs without exposing sensitive internals.

Detailed errors improve diagnosability, but they increase response size and require careful maintenance. Avoid returning every internal validation rule or exception message to clients.

Recommended Format

RFC 9457 defines the application/problem+json media type. Its standard fields are:

Field Purpose
type Stable URI reference identifying the problem category
title Short, human-readable summary of the problem type
status HTTP status code represented as a number
detail Explanation specific to this occurrence
instance URI reference identifying the specific occurrence

Extensions can add application-specific fields such as code, traceId, errors, or retryAfterMs. Extension names should be documented and namespaced where collision is possible.

Keep code stable even if the detail message changes. Clients should branch on the code, not exact English text. Avoid defining one unrelated JSON shape for validation errors and another for internal failures.

Choosing HTTP Status Codes

Status Use it when
400 Bad Request The request is malformed or cannot be parsed
401 Unauthorized Authentication credentials are missing or invalid; include WWW-Authenticate
403 Forbidden The caller is authenticated but not authorized
404 Not Found The requested resource does not exist
409 Conflict The request conflicts with the resource’s current state
412 Precondition Failed A conditional request’s precondition does not hold
415 Unsupported Media Type The request uses an unsupported content type
422 Unprocessable Content The request is syntactically valid but fails semantic validation
429 Too Many Requests The caller exceeds the rate limit; include Retry-After when known
500 Internal Server Error An unexpected server failure occurs
503 Service Unavailable The service is temporarily unable to handle the request

The distinction between 400 and 422 must be documented consistently. 401 means “not authenticated,” while 403 means “authenticated but not allowed.” A version conflict, duplicate idempotency key, or invalid state transition normally belongs under 409, not 500.

Example

A POST /orders request with the JSON body {"items":[{"sku":"ABC-123","quantity":0}]} receives 422 Unprocessable Content with Content-Type: application/problem+json.

The response body is: {"type":"https://api.example.com/problems/validation-error","title":"Request validation failed","status":422,"detail":"The order contains one or more invalid fields.","instance":"/requests/01J2ABCDEF56789","code":"VALIDATION_FAILED","traceId":"01J2ABCDEF56789","errors":[{"field":"items[0].quantity","code":"OUT_OF_RANGE","message":"Quantity must be between 1 and 100."}]}.

The type URI identifies the general validation problem, while instance and traceId identify this occurrence. The request may also include an Idempotency-Key header if the client needs safe retries.

Best Practices and Pitfalls

  • Use one error shape: Apply the same top-level structure across endpoints while allowing field-specific extensions.

  • Never expose stack traces: Stack traces, SQL statements, credentials, internal hostnames, and framework exceptions can disclose sensitive information.

  • Support correlation IDs: Return a trace or request ID and ensure it can be found in server logs.

  • Document retry behavior: Do not retry permanent errors such as 400 or 403. For 429, 502, 503, and 504, use bounded exponential backoff with jitter, honor Retry-After when supplied, and repeat non-idempotent operations only when an idempotency key prevents duplicate effects.

  • Handle idempotency explicitly: If an idempotency key is reused with a different request body, return 409.

  • Keep contracts stable: Existing error codes should retain their meaning. Add new fields or codes instead of changing established semantics.

  • Do not use 200 for failures: Success and failure statuses should accurately reflect HTTP response semantics.

  • Avoid vague messages: “Bad request” tells a client very little; identify the invalid field or conflict where safe.

  • Do not leak authorization details: A 404 may be preferable to 403 when revealing existence would disclose protected information.

A common interview mistake is designing success responses carefully while returning unstructured exception text for every failure. Interviewers usually look for a documented schema, correct status-code semantics, stable client-facing codes, safe messages, and a clear distinction between retryable and permanent failures.

19

What benefits does an API gateway provide?

An API gateway is a single entry point that enforces shared API contract rules for client requests (such as authentication, rate limiting, versioning, and a consistent error format) before they reach backend services. By applying these rules at one place, it lets multiple client-facing APIs present a stable, predictable contract without duplicating the same logic across every service.

Read full answer

Applies toall versions

The Problem It Solves

  • Scattered enforcement: Without one entry point, every service re-implements auth, rate limits, and error shapes, leading to inconsistent client experiences.

  • Client complexity: Clients would need to know the exact service locations, auth schemes per endpoint, and different error bodies.

  • Contract drift: As services evolve, it’s easy for status codes, headers, or error formats to differ between endpoints.

Key Benefits For The API Contract

  • Consistent authentication and authorization: The gateway can validate API keys, OAuth 2.0 access tokens, or JWTs and translate them to a trusted identity. This makes it clear when to return 401 (missing/invalid credentials) versus 403 (valid credentials, but not permitted).

  • Unified versioning: Route by /v1/, /v2/, or headers while keeping resource names plural (e.g. /orders) so clients can migrate without breaking all calls at once.

  • Rate limiting and abuse control: Apply per key, per client, or per route limits and return 429 with retry information when exceeded. This is a contract guarantee, not just an internal metric.

  • Request shaping and validation: Reject malformed payloads with 400 or semantically invalid ones with 422 before hitting services, enforcing the same rules for every resource.

  • Standardized errors: Return errors in application/problem+json (with type, title, status, detail) across all routes, instead of ad-hoc JSON.

  • Idempotency and safe exposure: The gateway can enforce or forward Idempotency-Key headers for non-idempotent operations. Remember: PUT and DELETE are idempotent, POST is not, and PATCH is not guaranteed to be. The gateway can reject duplicates on POST routes that require keys with 409 if a previous request is still in flight or already completed.

  • Safer client experience: Apply CORS, strip internal headers, and normalize pagination/filtering rules at the edge of the API so clients don’t have to guess per service.

Trade-Offs

  • Added latency: Every request pays a gateway hop. For same-datacenter calls this is often on the order of ~0.5 ms (rough order of magnitude), negligible for most REST calls, but can add up for chatty clients.

  • Single point of enforcement: A misconfigured rule (auth, rate limit, or transform) affects every route behind it.

  • Complexity cost: Policies (routes, scopes, per-route limits) need versioning and testing just like your API.

  • Risk of bloat: If you push business logic into the gateway, you make it hard to change without breaking the whole contract.

When To Use And When Not To

  • Use it when: You have multiple client types, need cross-cutting auth, shared rate limits, API versioning, or want a strict, uniform error contract for external consumers.

  • Do not use it when: You only expose a single internal service to trusted, known clients with no need for per-client throttling or versioning, or your team is too small to operate the policy set without creating a bottleneck. Only introduce it for the contract effects your clients actually rely on, not “just because”.

Concrete Example

  • Create order (client → API gateway): POST /orders with header Authorization: Bearer eyJhbGciOi..., header Idempotency-Key: 9f7a-4e3b, and Content-Type: application/json. The gateway enforces the contract and forwards a valid request.

  • Successful response: HTTP/1.1 201 Created, Content-Type: application/json, Location: /orders/o_942 with body {"id": "o_942", "status": "created"}.

  • Rate-limited error (enforced by gateway): HTTP/1.1 429 Too Many Requests, Content-Type: application/problem+json, Retry-After: 30 with body {"type": "https://api.example.com/errors/rate-limit", "title": "Too Many Requests", "status": 429, "detail": "Rate limit exceeded for this API key. Retry after 30 seconds."}

Interview Tips

  • What interviewers look for: Focus on contract benefits (consistent auth, status codes, error format, versioning) and explicit trade-offs, not just “hides services”.

  • Common mistake: Treating the API gateway as a place for business rules. Keep it to cross-cutting API concerns, and never rely on it to replace service-level authorization checks.

20

How do you design an API for file uploads?

A file-upload API should treat the file as a controlled resource, not as an unbounded request body. For small files, stream a multipart request through the service; for large files, create an upload session and have the client upload directly to object storage.

Read full answer

Applies toHTTP/1.1 and HTTP/2

Design the Contract

Start by defining the requirements:

  • Maximum file size, allowed formats, and whether multiple files are supported.

  • Authentication, authorization, quota, rate-limit, and retention rules.

  • Whether processing is synchronous or asynchronous.

  • Required metadata, such as filename, content type, checksum, owner, and business identifiers.

  • Error behavior for oversized, unsupported, malicious, or incomplete files.

Use plural resource names such as /v1/files. Return 201 Created when the file resource is created, 202 Accepted when an addressable request is accepted for asynchronous processing, and 204 No Content when deleting an upload session. Use 400 Bad Request for malformed multipart syntax, 401 Unauthorized for missing or invalid authentication, 403 Forbidden for insufficient authorization, 413 Payload Too Large for excessive files, 422 Unprocessable Content for semantically invalid metadata or unsupported formats, 409 Conflict for an idempotency-key conflict, and 429 Too Many Requests for quota or rate-limit violations.

Prefer Direct-to-Storage Uploads

Passing every file through the API service consumes application memory, connection capacity, and bandwidth. It also increases latency and makes recovery harder.

For larger files, use a two-phase design:

  1. The client creates an upload session through POST /v1/upload-sessions.

  2. The API authorizes the request and returns a short-lived, single-purpose signed upload URL.

  3. The client uploads directly to object storage.

  4. The service receives an event or notification and verifies the object’s existence, size, and optional checksum.

  5. The API records the metadata and exposes processing status.

The client may request completion, but its confirmation must not be trusted as proof. A missing, truncated, or substituted object must remain incomplete until the service verifies it. This design reduces application-server load, but adds session state, expiry handling, asynchronous status management, and cleanup of abandoned uploads.

Security and Validation

  • Authenticate before issuing permissions: verify identity and authorize access to the target account or resource.

  • Enforce size limits while streaming: Content-Length can help reject obviously oversized requests early, but it cannot replace enforcement of the actual received byte count.

  • Validate formats rather than trusting MIME types: use an allowlist of supported formats, validate file signatures where applicable, and generate safe server-side metadata. MIME sniffing is useful only as an additional signal.

  • Treat uploads as untrusted input: scan for malware and quarantine files until scanning completes.

  • Prevent path traversal: never use the original filename directly as a filesystem or object key.

  • Protect metadata: do not expose internal storage paths, credentials, or sensitive user information.

  • Restrict signed URLs: limit expiration, object key, operation, and content-length range where supported.

  • Encrypt in transit and at rest: use TLS and storage-provider encryption.

  • Avoid resource leaks: apply timeouts and cancellation, and configure lifecycle rules to remove abandoned sessions and temporary objects.

Reliability and API Semantics

Expose explicit processing states such as PENDING, AVAILABLE, REJECTED, and FAILED when asynchronous processing is required. For very large or interruption-prone transfers, support resumable multipart uploads with explicit part identifiers, checksum validation, completion, and abort operations.

Under HTTP semantics, PUT and DELETE are idempotent, POST is not, and PATCH is not guaranteed to be. Multipart file creation normally uses POST, so do not automatically retry it unless it has an idempotency key or is otherwise safely repeatable.

Scope idempotency keys by tenant and operation. Store the key, a request fingerprint, and the resulting response atomically: reuse with the same request returns the original result, while reuse with a different request returns 409 Conflict. Expire keys according to operational and business requirements.

Code Example

# TOKEN must contain a valid bearer token.
# invoice.pdf must exist in the current directory.
# -F sends multipart/form-data; the two fields are file and metadata.
curl -X POST "https://api.example.com/v1/files" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Idempotency-Key: upload-7f3a" \
  -F "file=@invoice.pdf;type=application/pdf" \
  -F "purpose=invoice"

A successful response could be:

HTTP/1.1 201 Created
Content-Type: application/json
Location: /v1/files/file_123

{
  "id": "file_123",
  "filename": "invoice.pdf",
  "content_type": "application/pdf",
  "size_bytes": 182344,
  "status": "AVAILABLE",
  "download_url": "https://api.example.com/v1/files/file_123/content"
}

Trade-offs and Best Practices

  • Small files: proxied multipart uploads are simpler and centralize authorization, but consume application resources.

  • Large files: direct-to-storage uploads improve throughput and scalability, but require session management, verification, expiry, and cleanup.

  • Synchronous processing: gives immediate results, but increases latency and couples availability to scanners and converters.

  • Asynchronous processing: improves responsiveness and failure isolation, but requires polling, events, or callbacks.

  • Storage model: object storage usually suits large binaries; keep searchable metadata and relationships in a database.

A strong design distinguishes accepting an upload from making the file available, and accounts for limits, authorization, validation, interrupted transfers, duplicate requests, orphan cleanup, and downstream failure.

21

How can caching be designed into an API?

Caching improves API performance by reusing previously computed responses or data instead of repeating expensive work. Placing caches at the edge, gateway, application, or database-access layers reduces latency, database load, and request cost, but introduces invalidation complexity and potentially stale data.

Read full answer

Applies toHTTP/1.1, HTTP/2, and HTTP/3 APIs

Where Caching Fits

A typical request path places caches according to the scope of the data:

  • CDN or edge cache: Serves public, frequently accessed responses close to users. Cross-region origin latency of roughly 50–150 ms can drop to tens of milliseconds when content is cached nearby.

  • Reverse proxy or API gateway: Caches complete HTTP responses and enforces shared caching policies.

  • Application cache: Stores computed objects or expensive query results, commonly in Redis or an in-process cache.

  • Database or service cache: Reduces repeated calls to databases and downstream services.

For example, a news API can cache rendered article responses at the edge while caching article records in Redis:

Client → CDN → API service → Redis → PostgreSQL

Designing the HTTP Cache Contract

For cacheable GET and HEAD responses, HTTP headers define cacheability:

  • Cache-Control: Controls whether and how long an intermediary may cache a response.

  • ETag: Identifies a response representation. A client can send If-None-Match to receive 304 Not Modified when its copy is current.

  • Last-Modified: Enables date-based conditional requests.

  • Vary: Identifies request headers that affect the representation, such as Accept-Encoding or Accept-Language.

  • Age: Reports how long the response has been cached by an intermediary.

Use public only for responses that may be shared between users. Use private when only a client cache may store the response. Use no-store for sensitive responses that must not be stored; merely omitting public does not prohibit heuristic shared caching.

Cache keys must include every parameter that changes the result, including tenant, locale, filters, sorting, and representation version.

Server-Side Cache Strategy

For application-owned data, cache-aside is usually the simplest approach:

  1. Read from the cache.

  2. On a miss, read from the authoritative database.

  3. Store the result in the cache with a TTL.

  4. On writes, update the database and invalidate or refresh the affected entry.

Other strategies have different costs:

Strategy Behavior Trade-off
Cache-aside Application manages reads, population, and invalidation Simple, but misses can cause a database spike
Read-through Cache loads missing data automatically Convenient, but couples the cache library to the data source
Write-through Writes update the cache synchronously Higher write latency; consistency still depends on failure handling and transaction boundaries
Write-back Writes update the cache and persist to the source later Lower write latency, but risk of data loss if cache persistence is not durable and harder consistency

Use event-driven invalidation when multiple services modify shared data, while retaining a TTL as a safety net. Versioned cache keys can prevent stale cache population when the version changes atomically with the authoritative data.

Trade-offs and Failure Modes

  • Stale data: A cached response may reflect an older database state. This is often acceptable for published articles or product catalogs, but risky for balances, inventory reservations, or permissions.

  • Cache invalidation: Removing the correct entry requires understanding every writer. A TTL limits staleness but does not guarantee immediate consistency.

  • Cache stampede: Many requests can miss one popular key simultaneously. Protect the origin with request coalescing, a short lock, randomized TTLs, or stale-while-revalidate behavior.

  • Cache dependency failure: A cache outage must not necessarily take down the API. Bypass the cache after a short timeout and use a bounded fallback rather than waiting indefinitely.

  • Memory and operating cost: Cached data consumes memory and requires eviction policies such as LRU or LFU.

  • Security leakage: Never share personalized responses across users. Use private only when client-side caching is acceptable and no-store when data must not be cached. Do not expose sensitive values in cache keys.

Do not add caching before measuring latency, query cost, and traffic patterns. A slow database query or inefficient endpoint usually benefits more from direct optimization than from masking it with a cache.

Code Example

A public article endpoint can expose an explicit edge and browser caching policy:

GET /articles?status=published&limit=20 HTTP/1.1
Host: api.example.com
Accept: application/json
HTTP/1.1 200 OK
Content-Type: application/json
Cache-Control: public, max-age=30, s-maxage=300, stale-while-revalidate=60
ETag: "articles-v42"

A subsequent conditional request avoids transferring the body:

GET /articles?status=published&limit=20 HTTP/1.1
Host: api.example.com
If-None-Match: "articles-v42"
HTTP/1.1 304 Not Modified
Cache-Control: public, max-age=30, s-maxage=300, stale-while-revalidate=60
ETag: "articles-v42"

Design Guidance

  • Start by profiling the endpoint and identifying the expensive operation.

  • Make cacheability an explicit part of the API contract, not an accidental implementation detail.

  • Use immutable, versioned URLs when practical to reduce invalidation requirements.

  • Set TTLs from the business tolerance for stale data.

  • Monitor hit ratio, origin traffic, eviction rate, latency, and cache-related errors.

  • Load-test cache misses and downstream failures, not only the warm-cache path.

  • Avoid caching mutable or authorization-sensitive responses unless the isolation model is carefully defined.

A common interview mistake is adding Redis without specifying ownership, keys, TTLs, invalidation, stampede protection, or behavior during cache failure.

22

How can an API handle high traffic volumes at scale?

Use horizontal scaling to run stateless API replicas and combine it with caching, bounded responses, rate limits, and asynchronous processing. Each technique shifts cost to latency, consistency, client complexity, or operational effort, so capacity should be driven by measured bottlenecks.

Read full answer

Applies toHTTP/1.1, HTTP/2, and HTTP/3 REST APIs

Make Requests Stateless and Bounded

High traffic first stresses request handling and downstream dependencies.

  • Stateless instances: Store session data in a shared service or in a signed token. Avoid sticky sessions because they complicate failover and horizontal scaling.

  • Horizontal scaling: Add replicas to increase throughput and limit the impact of a machine failure. The cost is additional infrastructure, deployment, and monitoring.

  • Bounded responses: Use cursor pagination, maximum page sizes, request-size limits, and field selection. Cursors perform better than deep offsets but are harder for clients to use.

  • Efficient payloads: Return only required fields, compress suitable responses, and use ETags for conditional requests.

At 10,000 requests per second with a 200 ms latency target, roughly 2,000 requests are in flight. Capacity plans must also include traffic peaks, retries, and downstream latency rather than relying on average throughput alone.

Cache Deliberately and Scale the Data Tier

Read-heavy APIs can overload a database before compute capacity becomes the bottleneck.

Strategy How it works Main cost
Cache-aside The API loads from cache and queries the database on a miss Stampedes and stale entries
Write-through Cache and backing store are updated synchronously Added write latency and failure coupling
Write-back The cache is updated first and persistence happens asynchronously Possible data loss and delayed durability
  • Invalidation: Define TTLs and update or evict entries when authoritative data changes. Monitor hit rate, eviction rate, and stale-read behavior.

  • Stampede protection: Coalesce concurrent requests for the same missing key and add small TTL jitter so many keys do not expire simultaneously.

  • CDN caching: Serve public, immutable responses with explicit Cache-Control headers near users.

  • Eviction: LRU favors recently accessed data, while LFU favors consistently popular data.

  • Database scaling: Fix slow queries and N+1 access first, then use connection pooling, asynchronous read replicas, and finally partitioning or sharding. Read replicas can serve stale data, while sharding adds routing, rebalancing, cross-shard queries, and distributed-transaction complexity.

Protect Capacity and Absorb Bursts

  • Rate limiting: Apply quotas per API key, user, tenant, route, or expensive operation, with global quotas only when justified. Token-bucket algorithms support bursts within a sustained limit.

  • Load shedding: Reject lower-priority work when dependencies are failing rather than exhausting every connection and worker.

  • Bulkheads: Reserve separate concurrency pools for critical operations so one dependency cannot consume all capacity.

  • Deadlines: Bound request and downstream-call duration so abandoned work cannot occupy resources indefinitely.

  • Asynchronous processing: For expensive or non-interactive work, return 202 Accepted with a status-resource URL rather than holding the connection open. Queues provide buffering, but at-least-once delivery requires idempotent consumers.

For example, POST /v1/orders with body {"product_id":"sku-123","quantity":2} can return 429 Too Many Requests, Retry-After: 2, Content-Type: application/problem+json, and body {"type":"urn:problem:rate-limit","title":"Too Many Requests","status":429,"detail":"Retry after 2 seconds."}.

Make Failure Safe

  • Timeouts and retries: Retry only transient failures, use exponential backoff with jitter, and cap attempts. Retries can multiply load during an incident.

  • Idempotency: PUT and DELETE are idempotent; POST is not; PATCH is not guaranteed to be. For retried creation requests, accept an Idempotency-Key and return the original result.

  • Circuit breakers: Stop calling a failing dependency temporarily and probe it gradually rather than consuming resources on repeated failures.

  • Graceful degradation: Return cached data, omit optional fields, or disable nonessential features instead of failing every request.

  • Availability versus durability: Availability measures successful service time, reliability covers correct and dependable behavior, and durability concerns surviving failures. A 99.9% availability target permits about 8.8 hours of downtime per year; 99.99% permits about 53 minutes.

Choose Strategies by the Bottleneck

Strategy Main benefit When it may be inappropriate
Stateless replicas More throughput and easier failover Low traffic or a small team unable to operate them
Caching Lower latency and database load Rapidly changing or highly personalized data
Read replicas Additional read throughput Read-your-write or immediate-consistency requirements
Sharding Large write and storage capacity A single database cluster has not been shown to be the bottleneck
Async processing Handles bursts without blocking clients The client requires an immediate final result
Microservices Independent deployment and scaling A monolith or modular design would meet the requirement

Measure with load tests and production telemetry before adding complexity. A common mistake is introducing caching, sharding, or microservices before identifying the actual constrained resource.

23

How does connection pooling improve API performance?

Connection pooling reuses a bounded set of already-established database connections instead of opening a new connection for every API request. It reduces connection setup latency and database churn, but an undersized pool can become a bottleneck while an oversized pool can exhaust the database.

Read full answer

Applies togeneral database connection pooling; examples use PostgreSQL 18

How It Works

A typical pool creates connections as needed, keeps them idle, and assigns one to each request that requires database access:

  1. The API request asks the pool for a connection.

  2. The pool returns an available connection or waits until one becomes available.

  3. The request executes its query or transaction.

  4. The connection is returned to the pool rather than closed.

  5. The pool later reuses that connection for another request.

Pooling can exist inside the API process, in a connection pooler such as PgBouncer, or in a managed platform layer. The application should always release the connection, including when an error occurs.

Connection pooling is different from HTTP keep-alive. HTTP pooling reuses TCP connections, sometimes avoiding repeated TLS handshakes; database pooling reuses authenticated database sessions.

Performance Benefits

Opening a database connection can involve TCP negotiation, TLS setup, authentication, and server-side session initialization. Reusing connections avoids repeating that work.

  • Lower latency: Requests do not pay the full connection-establishment cost.

  • Higher throughput: Expensive setup operations are amortized across many requests.

  • Reduced database churn: Fewer logins, handshakes, and abrupt connection termination events.

  • Controlled resource usage: A maximum pool size prevents an API instance from creating unlimited connections.

  • Burst handling: Prewarmed idle connections can serve sudden traffic spikes immediately.

The benefit depends on the workload. If connection setup is inexpensive and traffic is low, pooling may provide modest gains; under concurrent API traffic, it usually has a much larger effect.

Pool Sizing

For an application-local pool, the maximum possible connection count is:

API instances × maximum pool size per instance

For example, 10 API instances with a pool limit of 20 each could create 200 application-side database connections. This must fit within PostgreSQL’s connection budget, including administrative and background connections.

With a centralized pooler such as PgBouncer, distinguish the two layers: API instances connect to PgBouncer through client pools, while PgBouncer’s backend pool is sized according to PostgreSQL capacity and the pooling mode. Client-side pool limits do not directly determine the number of PostgreSQL connections.

Pool setting Purpose
Maximum connections Prevents one instance from overwhelming the database
Minimum idle connections Keeps a warm baseline for predictable latency
Idle timeout Removes unused connections after a period
Connection timeout Bounds how long a request waits for a connection
Maximum lifetime Rotates connections to limit stale-session issues

A queue with a bounded acquisition timeout is preferable to allowing requests to wait indefinitely. Timeouts should be coordinated with the API’s request deadline so a connection wait does not consume the entire request budget.

API Request Flow

Client → API service → Connection pool → PostgreSQL

For example, a request to GET /orders?customer_id=42 with a valid bearer token can return 200 OK with the JSON body {"orders":[{"id":"ord_123","status":"shipped"}]}.

The latency from the client includes network time, application processing, pool wait time, query execution time, and response transfer time. Pooling mainly reduces the connection-establishment portion; it does not make an inefficient query faster.

Failure Modes and Best Practices

  • Pool exhaustion: Requests queue and eventually time out. Monitor pool utilization, wait duration, acquisition failures, and query duration.

  • Stale connections: Network changes or database restarts can leave apparently open connections unusable. Validate connections when appropriate and keep lifetime settings conservative.

  • Connection leakage: Code that fails to return a connection permanently reduces capacity. Use scoped acquisition or try/finally logic.

  • Long-running transactions: A transaction holds its connection until completion. Keep transactions short and never perform external HTTP calls while holding one.

  • Unbounded pools: A pool larger than the database can support causes contention, memory pressure, and failures across unrelated services.

  • Incorrect timeout hierarchy: Connection acquisition and query timeouts should be shorter than or compatible with the overall API timeout.

  • Poor observability: Record pool name, wait time, timeout count, active connections, and idle connections as metrics.

Interviewers usually look for both sides of the trade-off: connection pooling improves latency and resource control, but pool sizing, acquisition timeouts, and leakage detection are essential to prevent the pool itself from becoming a system-wide bottleneck.

24

When should APIs use synchronous or asynchronous processing?

Synchronous processing makes the client wait for the operation to complete and return the result in the response, while asynchronous processing accepts the request, performs the work later, and exposes progress through a status resource or notification. The choice should follow the operation’s duration, the client’s latency requirements, and the system’s failure-handling needs.

Read full answer

Applies toHTTP API design using HTTP/1.1, HTTP/2, or HTTP/3

Decision Criteria

The problem is balancing fast responses with reliable execution. Holding a request open is simple, but long-running work consumes server resources, increases client timeouts, and can cause duplicate operations when clients retry.

Use synchronous processing when:

  • The operation completes quickly relative to the client’s timeout.

  • The caller needs the result immediately, such as validating input, checking inventory, or authorizing a checkout.

  • Strong, immediate feedback is more important than request decoupling.

  • The operation is short enough that the operational cost of a job system is unnecessary.

Use asynchronous processing when:

  • Work takes seconds or minutes, such as generating a large report, processing video, or sending bulk email.

  • Tasks produce fan-out, such as notifying thousands of users.

  • Traffic is bursty and a queue can smooth load against downstream systems.

  • The client can tolerate eventual completion.

  • The API must remain responsive even when workers or external dependencies are temporarily unavailable.

For example, an e-commerce checkout can synchronously authorize a payment, while exporting the completed order can run asynchronously.

HTTP Contract

Situation Recommended behavior
Immediate successful creation 201 Created
Long-running work accepted 202 Accepted with a job or operation URL
Completed job queried 200 OK with its status and result
Empty successful deletion 204 No Content
Malformed request 400 Bad Request
Valid syntax but invalid business input 422 Unprocessable Content
Missing or invalid authentication 401 Unauthorized
Authenticated but insufficient permission 403 Forbidden
Conflicting state or duplicate conflict 409 Conflict
Rate limit exceeded 429 Too Many Requests

202 Accepted means the server has accepted the work, not that it has completed successfully.

Reliability and Failure Handling

Both approaches require explicit timeouts and bounded retries. Retries should use exponential backoff with jitter and should only repeat safe or idempotent work.

  • Synchronous APIs: Use PUT and DELETE for idempotent effects. POST is not inherently idempotent, so create operations often accept an Idempotency-Key. A repeated request with the same key and equivalent payload should return the original result rather than create a duplicate.

  • Asynchronous APIs: Use a durable queue, idempotent consumers, and correlation or job IDs. If a database change and queue publication must be atomic, write the intent and an outbox record in one database transaction, then publish asynchronously.

  • Result delivery: Polling is simple but creates repeated requests. Webhooks provide lower client latency but require signed payloads, event IDs, retry schedules, and receiver-side deduplication.

  • Observability: Measure end-to-end completion time and failure rate, not only the initial HTTP response. Track queue depth, job age, retry count, dead-letter volume, and stuck jobs.

Asynchronous processing commonly provides at-least-once delivery, not exactly-once delivery. Consumers must therefore tolerate duplicate messages.

Trade-offs

Synchronous Asynchronous
Lower perceived latency when work is fast Faster acceptance for long-running work
Immediate result and simpler client logic Eventual result and more complex client state
Fewer infrastructure components Requires queues, workers, storage, and monitoring
Client and server are coupled during execution Work can continue after the response
Long operations consume request-handling capacity Queueing absorbs bursts and smooths load
Timeouts can cause ambiguous partial completion More explicit lifecycle and failure states

Do not use asynchronous processing for trivial operations or when users require an immediate answer. Its extra infrastructure is not justified merely because a task runs in a background thread. If an asynchronous workflow mutates shared state, clients may also need to tolerate eventual consistency; that is a property of the workflow’s consistency model, not an automatic consequence of asynchronous processing.

Practical API Shapes

  • Synchronous creation: A POST /v1/payments request with the body {"orderId":"order-8472","amount":4990,"currency":"USD"} returns 201 Created with the body {"paymentId":"pay_123","status":"authorized"}.

  • Asynchronous creation: A POST /v1/report-exports request with the body {"orderId":"order-8472","format":"pdf"} returns 202 Accepted, a Location of /v1/report-export-jobs/job_123, Retry-After: 2, and the body {"jobId":"job_123","status":"queued"}.

Best Practices

  • Validate cheap, essential parts synchronously; queue only the expensive work.

  • Define job states explicitly, such as queued, running, succeeded, and failed.

  • Expose a status endpoint and support cancellation only when it can be implemented reliably.

  • Store idempotency results for a documented period and scope keys by client and endpoint.

  • Avoid unbounded polling; use Retry-After, exponential backoff, or webhooks.

  • Monitor API acceptance separately from eventual job completion.

A common interview mistake is choosing asynchronous processing only because it “scales.” The stronger answer explains why the operation is long-running, how duplicate work is controlled, how clients receive results, and what additional operational cost the queue introduces.

25

What challenges arise when maintaining an API at scale?

Maintaining an API at scale means preserving a stable, predictable contract while traffic, clients, data models, and upstream dependencies continue changing. The main challenges are backward compatibility, performance, abuse prevention, documentation, observability, and coordinating changes without disrupting existing consumers.

Read full answer

Applies toHTTP/1.1, HTTP/2, and HTTP/3

Core Challenges

  • Backward compatibility: Existing clients cannot all be upgraded simultaneously. Adding an optional field is usually safe; changing a field’s type, meaning, or validation rules can break clients even when the HTTP status remains 200.

  • Versioning and migration: URL versions such as /v1/orders are simple but create maintenance overhead. Header or media-type versioning gives clients more control but can be easier to misuse. Prefer compatible evolution and clear deprecation notices over creating many versions unnecessarily.

  • Performance and capacity: Slow endpoints can become bottlenecks even when the application scales horizontally. Database queries, third-party calls, large responses, and synchronized operations often dominate latency.

  • Reliability: Retries can duplicate writes, partial failures can leave resources inconsistent, and dependencies can overload downstream systems. Clients need timeouts and predictable error responses.

  • Abuse and quota management: Public APIs need rate limits and protection against expensive queries or automated scraping. Require authentication and authorization where access is not intentionally public. Rate limiting reduces load but can reject legitimate traffic during traffic spikes.

  • Documentation and client education: Inconsistent examples, undocumented error codes, and undocumented limits create support costs and integration bugs.

Data and Pagination Decisions

Approach Advantages Costs and limitations
Offset pagination Easy to implement and navigate arbitrary pages Slower on large datasets; inserts or deletes can cause duplicates or skipped records
Cursor pagination Stable and efficient for large or changing datasets Clients cannot easily jump directly to an arbitrary page
Response filtering Lets clients request only needed fields Can produce expensive queries and many cache variants

Do not expose the database schema directly as the public API. It couples clients to internal storage decisions and makes later migrations unnecessarily expensive.

HTTP Semantics and Error Handling

  • GET, HEAD, OPTIONS, and TRACE are safe. GET, HEAD, PUT, and DELETE are idempotent.

  • POST is not idempotent, while PATCH is not guaranteed to be idempotent.

  • Use 201 with a resource location after creation, 204 for an empty successful response, 400 for malformed request syntax, 422 for semantically invalid input, 409 for state conflicts, and 429 when rate limits are exceeded.

  • Return a consistent error structure, preferably using application/problem+json, with a machine-readable code, a safe human-readable message, and, when useful, field-level details.

Example Contract

Exchange Method and path Status Headers and body
Create request POST /v1/orders — Authorization: Bearer <token>, Idempotency-Key: order-123, Content-Type: application/json; body: {"customerId":"cus_42","items":[{"sku":"sku_7","quantity":2}]}
Create response — 201 Created Location: /v1/orders/order_123; body: {"id":"order_123","status":"created"}
Rate-limited response — 429 Too Many Requests Retry-After: 30, Content-Type: application/problem+json; body: {"type":"https://api.example.com/problems/rate-limit","title":"Rate limit exceeded","status":429}

Operational Practices

  • Monitor latency, throughput, error rate, saturation, and usage by endpoint and client.

  • Track API adoption so deprecated fields or versions can be retired safely.

  • Use idempotency keys for retried POST operations that create resources or trigger payments.

  • Apply request timeouts, bounded retries with exponential backoff and jitter, circuit breakers, and bulkheads around unreliable dependencies.

  • Cache suitable responses, but define TTL, invalidation, stale-data behaviour, and stampede protection.

  • Publish an API specification, test backward compatibility in CI, and communicate deprecation dates.

The common mistake is treating scaling as only adding servers. API scale is primarily a contract-management problem: an endpoint that accepts ten times more traffic but forces clients to guess error meanings, pagination rules, or compatibility guarantees is not a scalable API.

26

What security concerns matter when designing a REST API?

API security protects REST API data, operations, and users from unauthorized access, leakage, abuse, and compromise. Secure design uses defense in depth while balancing protection against latency, availability, usability, and operational effort.

Read full answer

Applies toall REST API versions

Threat Modeling and Trust Boundaries

Before choosing controls, identify assets, actors, trust boundaries, and abuse cases, then rank risks by impact and likelihood.

  • Assets: customer data, credentials, business records, internal services, and administrative actions.

  • Actors: anonymous users, authenticated users, compromised clients, insiders, and external attackers.

  • Trust boundaries: internet-to-gateway, gateway-to-service, service-to-database, and service-to-third-party calls.

  • Likely threats: broken authentication, excessive permissions, injection, insecure direct object references (IDOR), SSRF, mass assignment, leakage, denial of service, and vulnerable dependencies.

  • Failure rule: reject requests when identity or policy cannot be verified; never fail open.

Apply additional controls to payment, personal-data, multi-tenant, and administrative APIs.

Authentication and Authorization

Authentication establishes identity; authorization decides whether that identity may perform an action.

Mechanism Appropriate use Important limitation
API key Server or automation identity Does not carry delegated user permissions
OAuth 2.0 + OIDC User delegation and integrations Requires token, scope, consent, and revocation management
JWT Short-lived signed tokens Revocation is less direct
Session cookie Browser applications Requires CSRF protection and secure cookie settings

Perform authorization inside the service, not only at a gateway.

  • Least privilege: issue narrow scopes and role permissions.

  • Object-level checks: verify access to the specific order, invoice, or user, not merely access to the endpoint.

  • Tenant isolation: scope every query and policy decision to the tenant.

  • Deny by default: reject unknown roles, actions, and routes.

  • JWT validation: verify the signature, issuer, audience, expiry, and allowed algorithm; never trust unverified claims.

Return 401 Unauthorized when authentication is missing or invalid and 403 Forbidden when an authenticated principal lacks permission.

Input Validation and Data Protection

Treat all request data as untrusted, including headers, query parameters, JSON bodies, files, and callback URLs.

  • SQL injection: use parameterized queries, never concatenate input.

  • Command injection: avoid shells; use APIs that accept argument arrays.

  • XSS: encode data for its output context; do not return unsafe HTML.

  • SSRF: allowlist destinations, block internal and metadata addresses, and revalidate resolved DNS results.

  • Mass assignment: explicitly list writable fields.

  • Resource exhaustion: cap body size, array length, pagination, and decompression expansion.

  • Sensitive data: minimize collection, define retention, encrypt at rest, and redact logs.

  • Passwords: use Argon2id, bcrypt, or scrypt with unique salts, not a fast general-purpose hash.

Use 400 Bad Request for malformed input and 422 Unprocessable Entity for syntactically valid data that violates business rules.

Transport, Abuse, and Webhooks

Use TLS 1.3 where supported, retain TLS 1.2 only for compatibility, enable HSTS, and avoid mixed content. Encrypt service-to-service traffic across untrusted boundaries.

Protect availability and cost with:

  • Per-client and per-user rate limits, endpoint quotas, and body-size limits.

  • 429 Too Many Requests with Retry-After.

  • Deadlines, timeouts, circuit breakers, and concurrency limits for expensive calls.

CORS controls cross-origin browser access; it is not authentication and does not stop non-browser clients. Cookie-authenticated APIs also require CSRF protection.

Webhook receivers should verify signatures with an HMAC, compare timestamps with the current time, use constant-time comparison, and deduplicate event IDs. Restrict outbound destinations to prevent SSRF.

  • Example request: POST /v1/orders, with Authorization: Bearer <access-token>, Idempotency-Key: 8f14e45f-ceea-467a-9f4e-5b8f9f47b21a, Content-Type: application/json, and body {"product_id":"prod_123","quantity":2}.

  • Example response: 201 Created, with Location: /v1/orders/ord_456 and body {"id":"ord_456","status":"created"}.

Store idempotency results under the caller and key so retries do not create duplicates. POST is not inherently idempotent; PUT and DELETE are, while PATCH is not guaranteed to be.

Errors, Logging, and Dependencies

Return RFC 9457 application/problem+json errors with a stable error type, correlation ID, and safe human-readable detail. Never expose stack traces, database details, or whether an account exists.

  • Log authorization failures, rate-limit events, and unusual access patterns.

  • Redact tokens, passwords, API keys, cookies, and unnecessary personal data.

  • Store secrets in a secrets manager, not source code or images; encrypt them and plan rotation.

  • Scan dependencies, generate an SBOM, and patch known vulnerabilities.

  • Protect administrative endpoints with MFA, restricted networks, and audit trails.

Trade-offs and Common Mistakes

A gateway can enforce TLS termination, coarse rate limits, and authentication, but object-level authorization belongs in the service. Each safeguard adds latency, state, or operational work, so choose controls based on risk rather than deploying every control everywhere. Do not use opaque identifiers as authorization, treat CORS as access control, or rely on a gateway alone for tenant isolation.

Common mistakes are conflating authentication with authorization, exposing raw upstream errors, signing webhooks without replay protection, and failing to isolate tenants. Interviewers look for a threat model, explicit trust boundaries, safe failure behavior, and an honest account of the operational cost of each safeguard.

27

How do you prevent injection attacks when designing APIs?

Injection prevention means treating every external value as untrusted and ensuring that values cannot alter the syntax of a database query, shell command, template, or other interpreter. The primary defense is parameterization, supported by strict validation, safe serialization, least privilege, and context-specific output encoding.

Read full answer

Applies toJava 17 with JDBC, PostgreSQL 16

Threat Model

An injection attack occurs when attacker-controlled data crosses an interpreter boundary and becomes executable instructions rather than plain data. Depending on the API, this can affect SQL, NoSQL queries, operating-system commands, templates, LDAP filters, or browser-rendered content.

Injection type Unsafe design Safer design
SQL Concatenate input into SQL Use prepared statements with bound parameters
NoSQL Build filter expressions from raw JSON Use typed driver methods and validate operators
Command Pass input through a shell Use argument arrays without a shell
Template Insert raw values into rendered HTML Enable automatic context-aware escaping
LDAP Construct filters from raw input Use allowlisted attributes and safe filter APIs
Browser output Return untrusted strings as HTML or scripts Return JSON and encode for the final rendering context

The same API may contain several injection surfaces. For example, a user-search endpoint might accept a sort parameter, an email filter, and a profile image filename.

Parameterize Every Interpreter

Use parameterized APIs for every value that can contain attacker-controlled data:

  • SQL: bind parameters with PreparedStatement or an equivalent query builder API.

  • NoSQL: use typed methods rather than constructing query documents from strings.

  • Shell: use process APIs such as Java ProcessBuilder or Python subprocess with argument lists and shell=false semantics.

  • Templates: use the framework’s escaping or sandboxing mechanisms.

Do not depend on escaping alone. Escaping rules depend on the interpreter, character encoding, and context; parameterization keeps data and executable syntax separate.

Also validate values that cannot be parameterized, such as sort columns or filter operators. These should be selected from a fixed allowlist rather than interpolated directly into SQL, even if they come from an internal client.

Validate at the API Boundary

Define and enforce schemas for request parameters, headers, path variables, and JSON bodies. Validation should distinguish malformed syntax from semantically invalid values:

  • 400 Bad Request: the request is syntactically malformed, such as invalid JSON.

  • 422 Unprocessable Content: the syntax is valid, but a field violates a domain rule.

  • 401 Unauthorized: authentication is missing or invalid.

  • 403 Forbidden: the caller is authenticated but not authorized.

Validation is defense in depth, not a replacement for parameterization. Attackers can discover encodings and edge cases that a regular expression does not anticipate.

For mass-assignment risks, use explicit request DTOs or schemas with allowlisted fields. Do not automatically bind every property supplied by a client to a database entity.

Control Output and Privileges

  • Return JSON with Content-Type: application/json and allowlist fields in the response model.

  • Never mark untrusted user content as executable HTML or script.

  • Apply context-specific output encoding when a downstream browser renders API data as HTML, CSS, JavaScript, or a URL.

  • Use a database role restricted to the minimum required tables and operations; separate migration privileges from runtime privileges.

  • Return generic errors without SQL text, stack traces, filesystem paths, or command output.

  • Use application/problem+json for a consistent error contract.

  • Treat WAF rules as an additional layer, not the primary protection.

Least privilege limits impact if one control fails. A compromised API process using a read-only database role should not be able to modify schemas, read unrelated tables, or execute administrative commands.

Code Example

This complete Java example validates an email, uses an allowlist for a non-parameterizable sort field, and retrieves a user through a parameterized PostgreSQL query with PreparedStatement. All parameters are bound with explicit setters and all JDBC resources are closed via try-with-resources.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Optional;
import java.util.Set;
import java.util.regex.Pattern;

public final class UserRepository {
    private static final Pattern EMAIL_PATTERN =
            Pattern.compile("^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$");

    private static final Set<String> ALLOWED_SORT_FIELDS =
            Set.of("createdAt", "email");

    public record User(long id, String email) {}

    public Optional<User> findByEmail(String email) throws SQLException {
        if (email == null || !EMAIL_PATTERN.matcher(email).matches()) {
            throw new IllegalArgumentException("Invalid email");
        }

        String sql = """
                SELECT id, email
                FROM users
                WHERE email = ?
                LIMIT ?
                """;

        try (Connection connection = DriverManager.getConnection(
                    System.getenv("DATABASE_URL"),
                    System.getenv("DATABASE_USER"),
                    System.getenv("DATABASE_PASSWORD"));
             PreparedStatement statement = connection.prepareStatement(sql)) {

            statement.setString(1, email);
            statement.setInt(2, 1);

            try (ResultSet resultSet = statement.executeQuery()) {
                if (!resultSet.next()) {
                    return Optional.empty();
                }

                return Optional.of(new User(
                        resultSet.getObject("id", Long.class),
                        resultSet.getString("email")));
            }
        }
    }

    public String resolveSortField(String sortField) {
        if (sortField == null || !ALLOWED_SORT_FIELDS.contains(sortField)) {
            throw new IllegalArgumentException("Unsupported sort field");
        }
        return sortField;
    }
}

A successful API response could look like:

GET /users?email=alice%40example.com HTTP/1.1
HTTP/1.1 200 OK
Content-Type: application/json

{"id":42,"email":"alice@example.com"}

An invalid email should receive a stable problem response without exposing internal details:

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

{"type":"urn:problem:validation-error","title":"Validation failed","status":422,"detail":"email is invalid"}

Best Practices and Trade-offs

  • Use allowlists for identifiers and operations. This is safer than blocklists but requires maintenance when supported options change.

  • Prefer typed APIs over string-built queries. This adds a small amount of code but removes an entire vulnerability class.

  • Keep database permissions narrow. This may complicate migrations, so privileged operations should run through a controlled deployment process.

  • Avoid raw error forwarding. Detailed errors help debugging but leak implementation details to attackers; log them securely server-side instead.

  • Test the contract with SQL metacharacters, unexpected operators, oversized values, malformed encodings, and second-order injection cases.

A common interview mistake is claiming that input validation or a WAF prevents SQL injection. The strongest answer identifies the interpreter, uses parameterization at that boundary, limits privileges, and explains how each additional control reduces risk without replacing the core defense.

28

What is CORS and why does it matter in API design?

CORS (Cross-Origin Resource Sharing) is a browser security mechanism that controls whether JavaScript running on one origin may read a response from another origin. It matters in API design because the server’s CORS policy becomes part of the contract for browser-based clients.

Read full answer

Applies toWHATWG Fetch Standard (Living Standard), current major browser versions

The Problem CORS Solves

Browsers enforce the same-origin policy: JavaScript can normally read a response only when the request’s scheme, host, and port match those of the page making the request.

For example, a page at https://app.example.com cannot directly read a response from https://api.example.com. CORS lets the API selectively authorize the browser to share that response with the page.

CORS governs script-readable responses. It does not block simple cross-origin requests from being sent, but a failed preflight prevents the actual request in a preflighted exchange from being sent. Non-browser clients such as curl, mobile applications, and server-to-server services do not enforce CORS.

How CORS Works

For some requests, the browser first sends an OPTIONS preflight request to determine whether the real request is permitted. A preflight is normally required when:

  • The method is not GET, HEAD, or POST.

  • The request contains a non-safelisted header such as Authorization.

  • The request’s Content-Type is not a safelisted value such as application/x-www-form-urlencoded, multipart/form-data, or text/plain.

Because application/json is not safelisted, JSON POST requests usually trigger a preflight. The important response headers are:

  • Access-Control-Allow-Origin: The origin allowed to read the response.

  • Access-Control-Allow-Methods: The methods permitted for the actual request.

  • Access-Control-Allow-Headers: The request headers permitted for the actual request.

  • Access-Control-Allow-Credentials: Whether the response may be exposed when the request uses credential mode include; it does not attach credentials.

  • Access-Control-Expose-Headers: Which additional, non-safelisted response headers script may read.

  • Access-Control-Max-Age: How long the browser may cache the preflight result.

A preflight normally receives a 2xx response, commonly 204 No Content, with the appropriate CORS headers.

Example Requests and Responses

For a credentialed JSON request, the browser first sends OPTIONS /orders to https://api.example.com with Origin: https://app.example.com, Access-Control-Request-Method: POST, and Access-Control-Request-Headers: content-type.

The server can return 204 No Content with Access-Control-Allow-Origin: https://app.example.com, Access-Control-Allow-Methods: POST, OPTIONS, Access-Control-Allow-Headers: content-type, Access-Control-Allow-Credentials: true, and Access-Control-Max-Age: 600.

The browser then sends POST /orders with Content-Type: application/json and Cookie: session=abc123. The API can return 201 Created with the same origin and credential headers and the JSON body {"id":"ord_123","status":"created"}.

For credentialed requests, the server must return an explicit origin. Browsers reject Access-Control-Allow-Origin: * together with Access-Control-Allow-Credentials: true.

Why It Matters in API Design

  • Web applications: Their frontend origins need an explicit policy.

  • Public APIs: A wildcard origin can be acceptable for non-credentialed public data, although an allowlist is safer by default.

  • Credentialed APIs: Allowed origins should be restricted, and responses should include Vary: Origin when their CORS headers vary by origin.

  • Third-party integrations: Browser-based integrations may require access from customer-controlled origins.

  • Error responses: They should include CORS headers; otherwise script may see a generic CORS failure instead of the actual 401, 409, or 429 status.

CORS is commonly implemented in API middleware or at an API gateway. The selected layer must handle both preflight and actual responses.

Security and Trade-Offs

CORS is not authentication or authorization and does not prevent every cross-origin request from reaching the API. A simple cross-origin POST can still cause a server-side side effect even when script cannot read the response.

Cookie-authenticated state-changing operations should also use anti-CSRF tokens and suitable SameSite cookie settings. Never treat CORS headers as proof that a caller is trusted.

The costs are extra preflight latency and traffic, allowlist configuration, and greater risk from broad policies. CORS is generally unnecessary for server-to-server or native-mobile integrations that do not make browser-originated requests; those clients still require authentication and authorization.

Common Pitfalls and Best Practices

  • Allowlist known origins instead of reflecting arbitrary Origin values.

  • Return Access-Control-Allow-Credentials: true only when credentials are genuinely required.

  • Include CORS headers on error and rate-limit responses.

  • Handle preflight requests without charging them against normal business-operation quotas.

  • Centralize CORS logic in shared middleware or a gateway rather than duplicating it across services.

  • Remember that authentication, authorization, rate limiting, and CSRF defenses remain necessary regardless of CORS policy.

A common interview mistake is treating CORS as a universal request block. Simple requests are sent regardless; a denied preflight prevents the corresponding actual request from being sent.

29

How does an API key control access to an API?

An API key is a credential that lets a server authenticate a client application and decide which resources, operations, and usage limits it may access. It is commonly used for server-to-server integrations and public APIs where the caller is an application or device rather than an end user.

Read full answer

Applies toall versions

How It Works

The server issues a key to a registered client. The client sends the secret with each request, usually in an HTTP header, and the server:

  1. Reads the key from the request.

  2. Locates the corresponding client record, potentially using a public key identifier or a keyed hash.

  3. Checks whether the key is active, unexpired, and permitted to perform the requested operation.

  4. Applies scopes, permissions, rate limits, quotas, and auditing rules.

  5. Rejects invalid or unauthorized requests.

An API key normally provides application-level authentication, not proof of a specific human user’s identity. When delegated user access or user identity is required, use OAuth 2.0 access tokens, with OpenID Connect when standardized user authentication and identity claims are also needed.

Request and Response Example

A request can authenticate with the key in the Authorization header: GET /v1/orders HTTP/1.1, Host: api.example.com, Authorization: ApiKey Bearer ak_live_7H3K9P2M, and Accept: application/json.

A valid request returns 200 OK with Content-Type: application/json and a body such as {"orders":[{"id":"ord_123","status":"processing"}]}.

A missing or invalid key returns 401 Unauthorized, Content-Type: application/problem+json, and a challenge such as WWW-Authenticate: ApiKey realm="api". The body can be {"type":"about:blank","title":"Unauthorized","status":401,"detail":"A valid API key is required."}.

A valid key that lacks permission should return 403 Forbidden. A rate-limited request should return 429 Too Many Requests and may include a Retry-After header.

Security Properties

  • Protect the key in transit: use HTTPS, preferably TLS 1.3; TLS 1.2 remains acceptable where necessary.

  • Prevent disclosure: do not put API keys in URLs, query parameters, source code, mobile applications, or logs. Query parameters are commonly recorded by proxies and monitoring systems.

  • Generate strong secrets: normally create at least 256 bits of cryptographically random data and display it only once.

  • Store keys safely: for generated high-entropy machine keys, store a keyed hash such as HMAC-SHA-256 using a protected server-side secret, or a suitable cryptographic hash. Use a slow password hash such as Argon2id when a low-entropy secret is user-chosen; slow hashing is usually unnecessary for randomly generated machine keys and can increase authentication cost.

  • Use separate keys per environment: never share production keys with development, testing, or staging systems.

  • Support rotation and revocation: issue replacements before expiring old keys and revoke compromised keys immediately.

  • Limit privileges: assign each key only the scopes, endpoints, network restrictions, and rate limits it requires.

Trade-offs and Alternatives

Mechanism Best suited for Main limitation
API key Identifying a trusted application or device Usually does not represent an end user
OAuth 2.0 access token Delegated user or service authorization More protocol and token-management complexity
OAuth 2.0 client credentials Service-to-service access Requires a token endpoint and credential management
JWT Distributed authorization using signed claims Revocation and key rotation require careful design
mTLS Mutual authentication between workloads Requires certificate and PKI operations

API keys are simple and inexpensive to validate, but a leaked key permits impersonation until it is revoked. OAuth 2.0 is preferable for delegated, user-specific, or frequently revocable access. Mutual TLS provides strong workload identity but adds certificate-management overhead. Do not use an API key when workload identity, fine-grained user delegation, or standards-based token exchange is required.

Best Practices

  • Treat an API key as a secret, not as a permanent public identifier.

  • Provide key IDs so one key can be revoked without invalidating every client.

  • Record the key ID, principal, operation, and result in audit logs, but never record the secret itself.

  • Define expiration, rotation, quota, and emergency-revocation procedures.

  • Return a generic authentication error without revealing whether a particular key exists.

  • Use idempotency keys for unsafe operations such as payment creation; these are distinct from API keys and prevent duplicate processing.

A common interview mistake is claiming that an API key proves the identity of a human user. It usually authenticates a client application; user identity and consent require a separate mechanism such as OpenID Connect, while delegated access normally uses OAuth 2.0.

30

How do you implement API authentication and authorization?

Authentication identifies who the caller is, while authorization determines what that caller may do. Implement them as separate layers: authenticate at the appropriate trust boundary, then enforce resource-level authorization in the service that owns the resource.

Read full answer

Applies toHTTP APIs using OAuth 2.0, OpenID Connect 1.0, and RFC 9457

Designing the Trust Boundaries

Start by identifying principals, protected resources, and permitted actions. For example, an e-commerce API might distinguish customers, support agents, inventory services, and administrators. Define scopes and permissions before implementing endpoints.

  • Users: identity through an OIDC provider.

  • External clients: OAuth 2.0 authorization flows.

  • Services: OAuth client credentials, mTLS, or workload identity.

  • Simple integrations: scoped, rotatable API keys.

A valid token establishes identity, not access: a customer must not read another customer’s order.

Implementing Authentication

For user-facing APIs, use the OAuth 2.0 authorization code grant with PKCE, normally with OIDC for identity. Avoid handling passwords in application services.

For service calls, choose:

  • OAuth client credentials: centrally issued tokens and scopes.

  • mTLS: cryptographic workload identity, with certificate-lifecycle costs.

  • Workload identity: for example, Kubernetes service accounts mapped to cloud IAM roles.

API keys should be scoped and rotatable. Store only a verifier server-side and distribute the key through a secrets manager.

For JWT access tokens, verify the signature and allowed algorithm, iss, aud, exp, nbf when present, required scopes, and tenant or client claims. JWTs are signed, not encrypted: do not put secrets or sensitive personal data in them. Local validation is fast, but revocation is harder than with opaque tokens. Use opaque tokens plus introspection for immediate revocation; short lifetimes only bound the stale-claim window.

Implementing Authorization

Enforce authorization in the service that owns the resource. A gateway may validate tokens and enforce coarse scopes, but it cannot replace ownership or business-rule checks.

  • Default deny: reject access unless policy explicitly permits it.

  • Least privilege: issue narrow scopes and permissions.

  • Resource-specific: verify ownership, tenant, and requested action.

  • Tenant-safe: derive tenant identity from verified claims or trusted relationships, never an untrusted request field alone.

  • Auditable: record the principal, action, resource, decision, and policy identifiers.

Use RBAC when permissions map naturally to roles; use ABAC when decisions depend on tenant, ownership, location, time, or state. Scopes such as orders.read provide coarse permissions, while object-level policies decide whether a customer may access a particular order.

Error Contract

Condition Status Response behavior
Missing, malformed, expired, or invalid token 401 Unauthorized Include WWW-Authenticate and request reauthentication
Valid identity but insufficient permission 403 Forbidden Explain the missing permission without exposing protected data
Hidden resource owned by another user 404 Not Found Use when concealment is preferable to confirming existence
Rate limit exceeded 429 Too Many Requests Include retry guidance when appropriate

Use application/problem+json consistently. Do not reveal different details for a nonexistent resource and one belonging to another user when that would disclose protected information.

Code Example

An OAuth token exchange might look like this; endpoint paths are deployment-specific:

POST /oauth2/token HTTP/1.1
Host: identity.example.com
Content-Type: application/x-www-form-urlencoded
Authorization: Basic <base64-encoded-client-credentials>

grant_type=client_credentials&scope=orders.read

HTTP/1.1 200 OK
Content-Type: application/json
Cache-Control: no-store

{
  "access_token": "<jwt-access-token>",
  "token_type": "Bearer",
  "expires_in": 300
}

The token permits reading an order:

GET /orders/o-123 HTTP/1.1
Host: orders.example.com
Authorization: Bearer <jwt-access-token>
Accept: application/json

HTTP/1.1 200 OK
Content-Type: application/json

{
  "id": "o-123",
  "status": "paid"
}

The same token cannot delete an order because deletion requires orders.write:

DELETE /orders/o-123 HTTP/1.1
Host: orders.example.com
Authorization: Bearer <jwt-access-token>

HTTP/1.1 403 Forbidden
Content-Type: application/problem+json
WWW-Authenticate: Bearer realm="orders", error="insufficient_scope", scope="orders.write"

{
  "type": "authorization-error",
  "title": "Forbidden",
  "status": 403,
  "detail": "Deleting an order requires the orders.write permission."
}

Trade-offs and Best Practices

Approach Benefit Cost or limitation
OAuth 2.0 and OIDC Standard federation, scopes, identity, and consent Protocol and integration complexity
JWT access tokens Fast local validation Difficult revocation; claims can become stale
Opaque tokens Centralized revocation Introspection adds network latency
API keys Simple deployment Limited identity, delegation, and fine-grained authorization
mTLS Strong workload identity Certificate distribution and rotation overhead

Use TLS 1.3 where supported, with TLS 1.2 as a secure fallback. Never log bearer tokens, API keys, passwords, or sensitive claims. Rotate signing keys and control public-key distribution.

OAuth and OIDC may be excessive for one closed integration that can use scoped keys or workload identity. Avoid mTLS when client fleets cannot manage certificates.

HTTP method semantics remain independent of authentication: PUT and DELETE are idempotent, POST is not, and PATCH is not guaranteed to be. The common mistake is treating a valid token as sufficient authorization; combine coarse scopes with resource-level policy.

31

What does an API Gateway do in microservices architecture?

An API Gateway is the entry point between external clients and internal microservices. It handles cross-cutting concerns such as routing, authentication enforcement, rate limiting, protocol translation, and request observability while leaving business logic inside the owning services.

Read full answer

Applies toAPI Gateway patterns in all versions

Core Responsibilities

  • Routing: Maps a public URL to the appropriate internal service, for example, /orders to the Orders API and /payments to the Payments API.

  • Authentication enforcement: Validates API keys or OAuth 2.0 access tokens before requests reach protected services.

  • Rate limiting: Protects downstream systems from excessive traffic and returns 429 Too Many Requests when limits are exceeded.

  • Request transformation: Converts between client and backend formats, such as adding internal headers or translating between HTTP and gRPC.

  • Policy enforcement: Applies coarse-grained rules for IP allowlists, request-size limits, CORS, and WAF policies.

  • Observability: Records request IDs, latency, status codes, and metrics for gateway-to-service requests.

The gateway should not own domain rules, database transactions, or business workflows. For example, deciding whether an order may be refunded belongs in the Orders or Payments service, not in the gateway.

Request Flow

A typical request follows this path:

Client → DNS/CDN → API Gateway → Internal load balancer → Microservice → Database

The gateway authenticates the caller, applies traffic policies, selects the target service, forwards the request, and returns the response. It may also add an X-Request-ID so logs from the gateway and downstream services can be correlated.

An API gateway differs from a load balancer:

Concern API Gateway Load balancer
Primary purpose API policy and protocol handling Distributing traffic across instances
Understands HTTP and application requests Usually May be L4-only or L7-aware
Authentication and rate limiting Common Rare
Request transformation Supported Uncommon

API Contract Responsibilities

The gateway can provide a stable public contract even when internal services evolve. For example, it can hide an internal gRPC service behind a public REST API.

However, teams must define which changes remain backward-compatible. Changing field names, status-code behavior, or authentication requirements may break clients even if internal implementations are unchanged.

HTTP method semantics still apply at the gateway: GET, PUT, and DELETE are idempotent, POST is not, and PATCH is not guaranteed to be. Unsafe create or mutation requests should use an idempotency key when clients or intermediaries may retry them.

A gateway may also aggregate several services into one response, but this increases latency, coupling, and failure propagation. Prefer independent endpoints when clients can make parallel requests.

HTTP Contract Example

For example, GET /orders/ord_123 with Authorization: Bearer access-token can return 200 OK, Content-Type: application/json, and the body {"id":"ord_123","status":"confirmed","total":49.95}.

If the caller exceeds its quota, the gateway can return 429 Too Many Requests with Retry-After: 30, Content-Type: application/problem+json, and a body such as {"type":"https://api.example.com/problems/rate-limit-exceeded","title":"Rate limit exceeded","status":429,"detail":"Retry the request after 30 seconds."}.

Trade-offs and Failure Modes

  • Latency: Every request receives an additional network hop and policy-processing cost, although a same-datacenter round trip is roughly 0.5 ms before processing overhead.

  • Availability: A gateway can become a single point of failure. Run multiple instances across failure domains and remove unhealthy instances automatically.

  • Operational complexity: Routing rules, credentials, certificates, policies, and gateway configuration require strong ownership and auditing.

  • Blast radius: A gateway bug can affect every service behind it. Keep the gateway focused on stable cross-cutting policies.

  • Scaling: Stateless gateways scale horizontally, but authorization checks, rate-limit counters, and request transformation can still become CPU-intensive bottlenecks.

  • Coupling: Excessive aggregation or business logic in the gateway makes independently deployable services less independent.

Internal service-to-service concerns such as mutual TLS and fine-grained traffic policy may be better handled by a service mesh, but that is a separate responsibility from the public API contract.

Best Practices and Interview Points

  • Keep the gateway thin and delegate business decisions to services.

  • Use 401 Unauthorized for missing or invalid authentication and 403 Forbidden for an authenticated caller lacking permission.

  • Use idempotency keys for unsafe create or mutation operations.

  • Configure timeouts, exponential backoff with jitter, circuit breakers, and bulkheads for downstream calls; retry only safe operations or requests protected by an idempotency key.

  • Return consistent problem+json errors for gateway-generated failures.

  • Version the public contract deliberately; internal service versions do not need to become client versions.

  • Monitor gateway latency, error rate, throttling, and per-route traffic.

A common mistake is treating an API gateway as a place for business logic. Interviewers usually look for a clear boundary between public API policy in the gateway and domain behavior in microservices.

32

What is a headless API?

A headless API exposes a system’s data and business capabilities over an API without bundling a specific user interface. Clients such as websites, mobile apps, kiosks, or third-party services can consume the same contract independently.

Read full answer

Applies toall versions; the headless pattern is protocol-independent, and the examples use REST over HTTP.

How It Works

The backend owns domain logic, validation, authorization, persistence, and workflows, while the presentation layer handles rendering and user interaction.

Headless describes this separation, not a particular wire protocol. A system can expose REST, GraphQL, or gRPC; the following examples use REST over HTTP.

A typical request flow is:

Client → API → Business logic → Database or external service

For example, an e-commerce product API might expose:

  • Request: GET /products/42 with Accept: application/json. Response: 200 OK with {"id":42,"name":"Desk lamp","price":49.99}.

  • Request: POST /products with Content-Type: application/json and body {"name":"Desk lamp","price":49.99}. Response: 201 Created, Location: /products/42, and body {"id":42,"name":"Desk lamp","price":49.99}.

  • Request: PATCH /products/42 with body {"price":44.99}. Response: 200 OK with {"id":42,"name":"Desk lamp","price":44.99}.

  • Request: DELETE /products/42. Response: 204 No Content with no body.

The client chooses how to display the response. A storefront might render HTML, a mobile app might render native controls, and an external integration might process the JSON directly.

Why It Exists

Traditional systems often combine the backend, templates, and UI in one application. That coupling makes it harder to reuse capabilities or support multiple client types.

A headless design keeps these concerns separate:

  • API contract: Resources, request formats, responses, and errors.

  • Domain logic: Validation, calculations, and business rules.

  • Client experience: Navigation, layout, and interaction.

  • Infrastructure: Databases, caches, queues, and external providers.

This is logical separation; it does not require every component to be deployed independently. For example, a news organization can use the same articles API for its website, mobile application, partner widgets, and internal reporting tools.

Benefits and Trade-offs

Benefit Cost or limitation
Supports multiple clients Every client must implement its own presentation logic
Enables independent frontend deployment Teams must manage more release pipelines
Encourages reusable domain capabilities The API becomes a long-lived client contract
Works well with SPAs and mobile apps More network requests and client-side rendering may increase latency
Supports third-party integration Requires robust authentication, authorization, and versioning

A headless API is not automatically high performance. Moving rendering to the client can reduce server workload but may increase browser work, JavaScript bundle size, and perceived loading time. Separating the frontend, API, and deployment pipeline also adds operational complexity.

API Design Considerations

  • Use meaningful resource-oriented paths: Prefer /orders/123/items over /getOrderItems?id=123.

  • Apply HTTP semantics correctly: GET, PUT, and DELETE are idempotent; POST is not, and PATCH is not guaranteed to be idempotent.

  • Make retried creates safe: Because POST is not inherently idempotent, support an idempotency-key mechanism, commonly the Idempotency-Key header. Scope keys to the caller and operation, and replay the original result for a repeated key.

  • Return standard status codes: Use 201 for creation, 204 for an empty successful response, 400 for malformed syntax, 422 for a well-formed but semantically invalid request, 401 for missing or invalid authentication, 403 for an authenticated caller lacking permission, 409 for conflicts, and 429 for rate limits.

  • Standardize errors: A consistent structure such as RFC 9457 Problem Details using application/problem+json helps clients handle failures reliably.

  • Version the contract: Additive changes are usually safer than changing field meanings or removing fields.

  • Secure the boundary: Authenticate callers, authorize access to each resource, and never rely on hidden UI controls for security.

  • Support pagination, filtering, and rate limits: These controls matter more when multiple independent clients depend on the API.

When to Use It

A headless API is a strong choice when several clients need the same capabilities, when the frontend must deploy independently, or when third parties need controlled access to business data.

It may be unnecessary for a small application with one web interface, simple workflows, and a small team. In that case, a modular monolith can provide clear code boundaries with less deployment and monitoring overhead. A common mistake is adopting microservices merely because an API is headless; the contract can be decoupled without independently deploying every service.

33

What are the main differences between GraphQL and RESTful APIs?

GraphQL exposes a typed schema through a typically common endpoint, allowing clients to request selected fields and related resources. RESTful APIs expose resources through URLs and use HTTP methods, status codes, and representations to define operations.

Read full answer

Applies toGraphQL September 2025 specification; REST over HTTP/1.1 and HTTP/2

Core Differences

Area GraphQL REST
Contract Server-owned, typed, usually introspectable schema No mandatory runtime type system; OpenAPI can describe the contract
Endpoint structure Usually one endpoint such as /graphql Multiple resource URLs such as /users/123/orders
Response shape Client selects fields in its operation Server returns a defined resource representation
Operations Queries, mutations, and subscriptions Primarily GET, POST, PUT, PATCH, and DELETE
Errors Execution errors often accompany partial data with 200 OK; malformed or invalid requests commonly return 400 HTTP status code communicates the outcome, such as 200, 201, 404, or 409
Over-fetching Clients request only the fields they need May require filtering, sparse fieldsets, or separate endpoints
Under-fetching Related resources can be requested in one operation May require several requests unless relationships are embedded
Caching Requires deliberate cache-key, transport, CDN, or client-cache design Naturally supports HTTP caching with headers, validators, and ETag
Real-time updates Defines subscriptions, but requires a transport such as WebSocket or SSE Commonly uses SSE, polling, or webhook-style event delivery
Evolution Additive schema changes and field deprecation Usually evolves through compatible representations or explicit versioning

HTTP method semantics remain important for REST: GET is safe and idempotent; PUT and DELETE are idempotent; POST is not idempotent; and PATCH is not guaranteed to be idempotent. GraphQL operation names are not HTTP methods, and sending a mutation through POST does not make that HTTP request idempotent.

Request and Response Model

A REST request addresses a resource:

GET /orders/42 → 200 OK with body {"id":42,"total":99.5,"status":"shipped"}.

A GraphQL request sends an operation to a common endpoint:

POST /graphql with body {"query":"query { order(id: 42) { id total status } }"} → 200 OK with body {"data":{"order":{"id":42,"total":99.5,"status":"shipped"}}}.

GraphQL can return both data and errors in the same response. If status fails to resolve but id succeeds, the response may contain partial data, an error entry for status, and HTTP 200. Clients must therefore inspect the response body rather than treating 200 as proof that every field succeeded.

Where GraphQL Helps

GraphQL is useful when several clients need different views of the same domain resources. A mobile application might request compact customer records, while an internal dashboard requests richer order details without maintaining a separate endpoint for every combination.

It can also reduce round trips. Instead of fetching an order, customer, and products through several REST calls, one GraphQL operation may request them together.

The trade-offs are substantial:

  • Resolver execution: Each selected field may trigger service work, creating N+1 database-query risks.

  • Authorization: Access must be enforced per operation and often per field.

  • Query cost: Deep or repetitive queries can consume substantial database and service capacity.

  • Caching: Standard HTTP field caching is less direct because GraphQL operations commonly use POST. Persisted queries can support cacheable GET requests, but CDN keys, headers, and cache policy must be designed correctly.

  • Persistence: Normalized client caches can reduce repeated network requests, at the cost of cache invalidation and normalization complexity.

  • Observability: Metrics and traces must account for operation complexity, resolver timing, and field-level errors.

Where REST Is Usually Better

REST remains a strong choice when the API represents a small, stable set of resources and clients benefit from standard HTTP semantics. It is usually simpler to cache with intermediaries, debug with standard HTTP tools, and evolve as conventional public APIs.

Its trade-offs are over-fetching, under-fetching, endpoint proliferation, and additional round trips when clients need related resources. Those costs are often acceptable for simple, cache-heavy, or resource-oriented systems.

REST is also preferable when independent resource caching and conventional status-code behavior matter more than client-shaped responses. Gateways can provide coarse authentication and rate limiting for both GraphQL and REST, but resource- or field-level authorization generally belongs in the service where the application can evaluate ownership and permissions accurately.

Practical Selection Guidance

  • Choose GraphQL for multiple client types, highly variable response needs, and complex related-resource access where reducing round trips matters.

  • Choose REST for simple resource APIs, cache-heavy workloads, public contracts that should follow standard HTTP behavior, or teams with limited GraphQL operational experience.

  • Consider both when different consumers have different needs: a stable REST API for simple integrations and a GraphQL API for specialized applications.

GraphQL does not eliminate API design work; it replaces much endpoint design with schema design while introducing resolver performance, authorization, caching, and error-handling challenges.

34

What is gRPC and how is it used in API design?

gRPC is a schema-driven RPC framework commonly used for low-latency service-to-service APIs. It defines methods and message types in Protocol Buffers files, generates client and server code, and typically transmits compact binary messages over HTTP/2.

Read full answer

Applies togRPC 1.x with proto3 Protocol Buffers and grpcurl 1.x

What It Solves

Traditional JSON-over-HTTP APIs are easy to inspect and consume, but teams often pay costs from:

  • Large payloads: JSON repeats field names and uses human-readable text.

  • Duplicated contracts: Client and server models can drift apart.

  • Manual serialization: Every service maintains its own encoding and validation logic.

  • Weak tooling: Code generation, mocking, and contract testing require additional work.

For example, a checkout service might call a product catalog through gRPC to retrieve pricing and availability. The shared .proto contract generates strongly typed clients, while the server remains independently deployable.

How gRPC Fits the API Design

  • Service and method definitions: A service exposes named operations such as GetProduct or CreateOrder.

  • Schema-first contracts: Request and response messages are declared in .proto files and become the source of truth. gRPC statuses are runtime values; optional typed error-detail messages can also be defined in the schema.

  • Code generation: Protobuf tooling generates client stubs, server interfaces, and message implementations for languages such as Java, Go, Python, and C#.

  • Four calling styles:

  • Unary: one request, one response.

  • Server streaming: one request, multiple responses.

  • Client streaming: multiple requests, one response.

  • Bidirectional streaming: concurrent streams in both directions.

  • Standard status handling: gRPC uses codes such as OK, INVALID_ARGUMENT, NOT_FOUND, PERMISSION_DENIED, and RESOURCE_EXHAUSTED, rather than treating HTTP status codes as application semantics.

  • Deadlines and cancellation: Clients specify a deadline, allowing servers to stop unnecessary work. Cancellation propagates through the call.

  • Metadata: Authentication tokens, tracing information, and request identifiers travel separately from application messages.

gRPC does not inherit REST semantics automatically. For example, REST PUT and DELETE are idempotent, POST is not, and PATCH is not guaranteed to be. A gRPC method that creates an order should therefore include an idempotency key and implement server-side deduplication if clients may retry it.

Trade-offs

Approach Strengths Main costs
gRPC Compact payloads, strong contracts, code generation, streaming, efficient bidirectional communication Less browser-friendly, more tooling, specialized debugging and proxy requirements
REST with JSON Familiar HTTP semantics, easy inspection, broad client support Less type-safe by default unless schema validation and generated models are added
GraphQL Flexible field selection and schema discoverability Higher gateway complexity and risk of expensive or complex queries

Use gRPC when internal services exchange many typed requests, latency matters, or both sides can adopt schema-driven development. It can also serve public APIs through a gateway or gRPC-Web, but this adds an HTTP translation layer and may not support every gRPC feature.

Avoid gRPC alone for browser-oriented CRUD APIs, cache-heavy public content, or environments where clients cannot generate gRPC stubs. Cross-region calls still cost roughly 50–150 ms in network latency, so serialization savings will not remove geographic latency.

Code Example

The following contract defines a unary product lookup:

syntax = "proto3";

package product.v1;

message GetProductRequest {
  string product_id = 1;
}

message Product {
  string id = 1;
  string name = 2;
  int32 price_cents = 3;
  string currency = 4;
}

service ProductService {
  rpc GetProduct(GetProductRequest) returns (Product);
}

A local client can invoke it with grpcurl, using the protobuf JSON mapping only at the command-line boundary:

grpcurl -plaintext \
  -import-path . \
  -proto product.proto \
  -d '{"productId":"p-123"}' \
  localhost:50051 \
  product.v1.ProductService/GetProduct

On the HTTP/2 wire, this is equivalent to POST /product.v1.ProductService/GetProduct; the native body uses gRPC’s Protocol Buffers framing rather than raw JSON. A successful call returns gRPC status OK, mapped to HTTP 200 OK, with this JSON-formatted result from grpcurl:

{
  "id": "p-123",
  "name": "Mechanical Keyboard",
  "priceCents": 4999,
  "currency": "USD"
}

-plaintext is appropriate only for local development. Production traffic should use TLS, normally with TLS 1.3 where supported.

Best Practices and Pitfalls

  • Treat .proto files as public contracts: Preserve field numbers, never reuse removed numbers, and introduce incompatible changes through a new package or service version.

  • Set deadlines everywhere: Without them, slow dependencies can accumulate and exhaust server resources.

  • Retry only safe operations: Use exponential backoff with jitter and idempotency for operations that may be repeated.

  • Use standard statuses: Map domain failures consistently; do not report every error as INTERNAL or UNKNOWN.

  • Keep credentials out of messages: Send OAuth bearer tokens through gRPC metadata and validate them at the service boundary.

  • Plan operational support: Load balancers, gateways, tracing, and packet inspection must understand gRPC and HTTP/2.

Interviewers commonly look for a discussion of latency, schema evolution, observability, and failure handling. The most common mistake is choosing gRPC solely for speed without considering client compatibility and the operational cost of a protobuf-based ecosystem.

35

How can WebSockets enhance real-time API functionality?

WebSockets provide a persistent, bidirectional connection over which a client and server can exchange messages immediately, reducing the latency and overhead associated with repeated HTTP polling. They complement traditional request-response APIs by supporting live updates, continuous data streams, and client-to-server events.

Read full answer

Applies toWebSocket protocol (RFC 6455) and modern web browsers

Why WebSockets Exist

Traditional HTTP APIs work well for CRUD operations, but real-time products often need continuous communication:

  • A trading dashboard needs price updates without the browser polling every second.

  • A chat application must deliver new messages and send typing indicators.

  • An IoT platform needs to receive device telemetry as it occurs.

  • A collaborative editor must broadcast each user’s changes to other participants.

Without WebSockets, clients typically poll a REST endpoint. Polling introduces unnecessary requests, delayed updates, and higher server load. WebSockets maintain one connection through which both sides can send data whenever needed.

Capabilities

  • Server push: The server can send notifications, events, or incremental data without another HTTP request.

  • Bidirectional messaging: Clients can send commands, telemetry, presence information, or application events over the same connection.

  • Low-latency updates: Messages arrive as events occur rather than at the next polling interval.

  • Persistent connections: The connection remains open, avoiding repeated TCP and TLS setup costs.

  • Efficient streaming: Applications can transmit ordered text or binary data incrementally.

WebSockets do not automatically guarantee low end-to-end latency. Network distance, server processing, queues, and congested connections still affect delivery time.

HTTP Handshake and Message Example

A WebSocket connection begins with an HTTP upgrade request. The client sends GET /ws HTTP/1.1 with headers including Host: api.example.com, Upgrade: websocket, Connection: Upgrade, Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==, and Sec-WebSocket-Version: 13. The server responds with 101 Switching Protocols, Upgrade: websocket, Connection: Upgrade, and Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=.

Interaction Example
Initial state request GET /v1/orders/ord_456
Initial state response 200 OK with {"orderId":"ord_456","status":"processing"}
Live update Server text frame: {"schemaVersion":1,"type":"order.updated","eventId":"evt_123","occurredAt":"2025-01-15T10:30:00Z","data":{"orderId":"ord_456","status":"shipped"}}

After the handshake, WebSocket messages do not use HTTP paths or status codes. The application defines its own message types and schemas, including versioning, identifiers, timestamps, and duplicate or replay semantics.

Reliability and Scaling

A production design must address several failure modes:

  • Disconnections: Clients should reconnect with exponential backoff and jitter rather than immediately reconnecting in a tight loop.

  • Lost messages: The protocol does not guarantee that every application message is delivered. Include sequence numbers or event IDs when the application needs deduplication or replay.

  • Stale connections: Use WebSocket ping/pong frames or application-level heartbeats to detect broken connections.

  • Overload: Apply connection limits, per-user quotas, message-size limits, and backpressure.

  • Horizontal scaling: Route connections through infrastructure that supports long-lived connections. Use Kafka or another retained log for durable event distribution and replay; Redis Pub/Sub can provide ephemeral live fan-out, but it does not retain messages for later recovery.

  • Deployment: Drain connections gracefully so servers can terminate without repeatedly interrupting active sessions.

  • Ordering: TCP preserves frame order within one connection, but concurrent event producers may still produce events out of logical order.

Exactly-once delivery is not provided by WebSockets. If an event changes business state, the event handler should be idempotent.

Trade-offs and Alternatives

Approach Direction Main advantage Main limitation
HTTP polling Client to server Simple and widely compatible Higher latency and request overhead
Server-Sent Events Server to client Simple over HTTP with automatic reconnection One-way communication
WebSockets Bidirectional Low-latency, full-duplex messaging Connection lifecycle and scaling complexity
gRPC streaming Bidirectional Typed contracts and efficient binary transport More infrastructure and browser/tooling constraints

Use WebSockets when both sides benefit from frequent, immediate communication. Do not use them for ordinary CRUD requests, infrequent updates, or workflows naturally handled with HTTP request-response semantics. A hybrid API often works best: REST for initial state and commands, WebSockets for subsequent live updates.

Best Practices and Security

  • Use wss:// in production and reject unauthenticated connections.

  • Authenticate browser clients through a secure cookie during the handshake or a short-lived connection ticket; avoid long-lived credentials in query strings because URLs may be logged.

  • Validate the Origin header and still authorize every subscription or message.

  • Define explicit limits for message size, connection count, subscriptions, and outbound queues.

  • Version the event schema and document compatibility rules.

  • Make reconnecting clients recover missed state through an event ID, cursor, or explicit resynchronization endpoint.

  • Separate notification channels from business commands when different reliability requirements apply.

Interviewers typically look for a clear explanation of persistent bidirectional communication, reconnection and event replay, connection-state scaling, and an honest comparison with polling and server-side streaming. A common mistake is adding WebSockets without designing authentication, overload control, or recovery after disconnections.

36

Which tools and frameworks support API development and testing?

A practical API toolchain combines a server framework, an API client, contract and mock tooling, automated tests, and load and security testing. The best choices depend on the API style, language, deployment environment, and required CI/CD automation.

Read full answer

Applies toOpenAPI 3.1 and current stable releases of the other listed tools

Core Development Stack

Choose the framework that best fits the application and team:

API style Common implementations Useful development tools
REST FastAPI, Flask, Express.js, NestJS, Spring Boot, ASP.NET Core Bruno, Insomnia, Postman, curl, Swagger UI, Redoc
GraphQL Apollo Server, GraphQL Yoga, Strawberry GraphiQL, GraphQL Code Generator, schema linters
gRPC grpc-java, grpc-go, grpcio, grpc-dotnet grpcurl, Buf CLI, Protobuf language plugins

Additional supporting tools include:

  • OpenAPI 3.1: Defines an HTTP API contract independently of its implementation.

  • OpenAPI Generator: Generates clients, models, and server stubs, reducing repetitive contract-handling code.

  • Swagger UI and Redoc: Render documentation from an OpenAPI specification; Swagger UI also includes a request console.

  • Docker and Testcontainers: Run services and real dependencies consistently on developer machines and in CI.

  • OpenTelemetry: Adds traces, metrics, and logs so failures can be diagnosed across service boundaries.

A large toolchain improves automation and consistency but adds configuration maintenance, upgrade work, and onboarding effort. A small service may need only a framework, one API client, and a CI test script.

The API Testing Pyramid

Different testing levels catch different failures:

Test level Purpose Example tools
Unit Tests handlers, validation, and business logic in isolation Language test frameworks and mocking libraries
Contract Verifies consumer-provider compatibility Pact
Schema validation Checks payloads against the declared contract OpenAPI schema validators
Mock Simulates unavailable or slow dependencies WireMock, Mockoon
Integration Tests the API against databases, queues, and other services Testcontainers, REST Assured, Supertest
End-to-end Tests a complete user journey Playwright, Selenium
Performance Measures latency, throughput, saturation, and errors k6, Artillery, JMeter
Security Finds some common injection and configuration weaknesses OWASP ZAP

Mocks are useful when an external service is unavailable, but excessive mocking can let integration defects escape. Prefer real containers for infrastructure dependencies and Pact-style contract tests for independently deployed consumers.

Contract-First Workflow

A contract-first workflow usually proceeds as follows:

  1. Define the API using OpenAPI 3.1, GraphQL SDL, or Protocol Buffers.

  2. Validate the specification and review it with API consumers.

  3. Generate documentation, models, or mock servers where supported.

  4. Implement the service against the contract.

  5. Run contract, integration, and end-to-end tests.

  6. Publish the final specification and verification results.

This reduces accidental breaking changes, especially when clients cannot be deployed at the same time as the server. Its cost is additional contract design and governance; a small internal API owned by one team may be adequately served by a reviewed design document and CI contract checks.

Example REST Request and Response

API clients such as Bruno, Insomnia, and Postman support saved requests, environment-specific values, assertions, and reusable collections. curl remains useful for quick checks and CI scripts.

Request Response
GET /orders/ord_123 with Accept: application/json 200 OK with Content-Type: application/json and body {"id":"ord_123","status":"paid","total":49.95}

The same request can become an automated collection with assertions on status, headers, schema, and response fields. Newman, for example, can execute Postman collections from a CI pipeline.

Load and Security Testing

Functional tests do not establish capacity. Use k6, Artillery, or JMeter to model realistic traffic and identify bottlenecks such as database connection exhaustion or slow downstream calls. Run tests in an environment representative of production; developer-laptop results are not reliable capacity estimates.

Use OWASP ZAP or a similar scanner to detect some injection, missing-header, and exposed-route issues. Automated scanning complements rather than replaces threat modeling, dependency scanning, authentication tests, and authorization checks.

Practical Selection and Pitfalls

A balanced stack might use OpenAPI for the contract, Swagger UI for documentation, a native framework for implementation, Testcontainers for integration tests, WireMock for external-service simulation, Playwright for critical journeys, k6 for performance, and ZAP for security scanning.

Do not adopt every tool by default. Before adding one, decide who maintains its configuration, where it runs in CI, and which failure it is intended to detect. Interviewers generally look for a repeatable workflow and explicit trade-offs rather than a long list of product names.

37

How to test API performance and which metrics to track?

API performance testing applies controlled, repeatable traffic to an API implementation and measures it against explicit SLOs for latency, throughput, errors, and resource use. It finds bottlenecks and failure modes before production; receiving 200 responses alone proves neither acceptable latency nor reliability.

Read full answer

Applies toHTTP APIs (all versions); k6 v1.x for the code example

What To Test

The problem performance testing solves is uncertainty about behavior under realistic and extreme demand, including queuing, resource exhaustion, and dependency failures.

  • Load testing: Apply expected traffic and verify throughput, latency, and error-rate SLOs.

  • Stress and breakpoint testing: Increase load beyond the expected peak to find the point where latency or errors degrade sharply.

  • Spike testing: Apply a sudden burst to test autoscaling, connection pools, queues, and rate limits.

  • Soak testing: Sustain load for hours to reveal memory leaks, connection leaks, and exhaustion.

  • Fault injection: Combine load with latency or dependency failures to validate failure handling.

Metrics To Track

Metric What it shows Important notes
Latency (p50/p90/p95/p99) Request duration Prioritize tail percentiles. Same-datacenter network round trips are roughly 0.5 ms and cross-region trips roughly 50–150 ms, depending on the path.
Throughput Completed requests per second Pair it with success and error rates; more traffic with worsening p99 is not an improvement.
Error rate Fraction of failed requests Track 4xx and 5xx separately. Exclude contractually expected 4xx responses from server-failure calculations.
TTFB Time to the first response byte Helps distinguish network, gateway, and application-processing delays.
Saturation Resource pressure Track CPU, memory, queue depth, request concurrency, and database or HTTP connection-pool wait time.
Client outcome Timeouts and transport failures Keep these separate from server-generated statuses such as 504.
Test success ratio Successful eligible responses divided by all eligible responses This is a test result, not an annual availability SLA. For context, 99.9% uptime is about 8.8 hours/year and 99.99% about 53 minutes/year.

How To Run It

  1. Define SLOs and representative requests: For example, GET /orders/123 should return 200 OK with {"id":"123","status":"paid"} within an agreed p99 latency.

  2. Model realistic traffic: Mix endpoints, methods, payloads, authentication, and think time. Tools such as k6, Locust, JMeter, or Artillery are examples, not substitutes for a representative workload.

  3. Control the environment: Use an isolated, production-like environment and test from relevant same-region, multi-AZ, and cross-region locations. Do not generate uncontrolled traffic on shared production.

  4. Observe the complete path: Instrument the API, cache, database, and dependencies. For caches, test hits, misses, TTL expiry, invalidation, LRU/LFU eviction, stampede protection, and the acceptable stale-data window across cache-aside, write-through, and write-back designs.

  5. Inject failures safely: Verify bounded timeouts, retries with exponential backoff and jitter, circuit breakers, bulkheads, health checks, graceful degradation, and that shared dependencies are not single points of failure.

  6. Handle retries correctly: Do not automatically replay an ambiguous POST timeout. If supported, reuse the same idempotency key for one logical operation; otherwise reconcile its status. PUT and DELETE are idempotent, POST is not, and PATCH is not guaranteed to be.

Code Example

This k6 script maintains a fixed arrival rate, which helps expose queueing and tail latency. Replace the URL, rate, duration, and thresholds with the endpoint’s actual values and SLOs.

import http from 'k6/http';
import { check } from 'k6';

const baseUrl = __ENV.BASE_URL || 'http://localhost:8080';
const orderId = __ENV.ORDER_ID || '123';
const headers = { Accept: 'application/json' };

if (__ENV.API_TOKEN) {
  headers.Authorization = `Bearer ${__ENV.API_TOKEN}`;
}

export const options = {
  scenarios: {
    orders: {
      executor: 'constant-arrival-rate',
      rate: 20,
      timeUnit: '1s',
      duration: '2m',
      preAllocatedVUs: 20,
      maxVUs: 100,
    },
  },
  thresholds: {
    http_req_duration: ['p(95)<500'],
    http_req_failed: ['rate<0.01'],
    checks: ['rate>0.99'],
  },
};

export default function () {
  const response = http.get(
    `${baseUrl}/orders/${encodeURIComponent(orderId)}`,
    { headers }
  );

  check(response, {
    'GET /orders/{id} returns 200': (r) => r.status === 200,
  });
}

Trade-offs

  • Accuracy versus cost: Realistic journeys require more scripts, test data, and compute.

  • Synthetic versus production traffic: Synthetic tests are reproducible but may miss organic traffic shapes and client behavior.

  • Isolation versus realism: Production-like environments reveal more than unit environments, but uncontrolled stress tests can cause outages.

  • Scope: Performance testing does not replace functional, contract, or security testing and should not be used as their substitute.

Common Pitfalls And Interview Takeaway

  • Reporting only averages hides tail latency; p99 also needs enough samples to be meaningful.

  • Testing only cached reads can conceal database latency and cache-stampede behavior.

  • Test representative pagination because deep offset pagination can be much more expensive than cursor pagination.

  • Test each deployed API version explicitly rather than assuming behavior is identical.

  • Common mistake: choosing an arbitrary RPS target without SLOs, environment isolation, status-code breakdowns, or idempotency handling. Interviewers look for an SLO-driven, full-path approach with explicit trade-offs.

38

What is API contract testing in service development?

API contract testing verifies that an API provider and its consumers agree on the expected requests, responses, and error behavior. It detects incompatible changes before they reach production by testing the published contract rather than relying only on implementation details or a shared integration environment.

Read full answer

Applies toall versions of REST, GraphQL, and gRPC APIs

The Problem It Solves

In a distributed system, a provider may change an API without realizing that a consumer depends on the old behavior. For example, a service might rename the response field customer_id to customerId. Unit tests still pass, and the provider’s tests still pass, but the consumer fails in production.

Contract testing replaces some late integration failures with fast, isolated checks. The contract becomes an explicit, executable agreement between teams.

This does not eliminate integration testing. It complements tests that exercise the complete deployed system.

How It Works

A typical consumer-driven contract-testing workflow is:

  1. The consumer describes the interactions it expects from the provider.

  2. These expectations become an executable contract, often using a framework such as Pact.

  3. The provider runs contract verification against its implementation.

  4. CI fails if the implementation no longer satisfies the contract.

  5. Contract changes are reviewed when they could affect other teams.

A contract may specify:

  • Request expectations: HTTP method, path, headers, query parameters, and body.

  • Response expectations: Status code, headers, and response schema.

  • Error behavior: Required error codes and machine-readable error structures.

  • State transitions: Whether a failed request may be safely retried.

  • Authentication rules: The required authentication mechanism or relevant header presence.

There are two common forms:

Approach Contract source Main benefit
Consumer-driven contract testing Expectations declared by API consumers Detects changes that matter to actual consumers
Provider schema verification A schema published by the API provider Ensures responses conform to a centralized specification

These approaches can be combined, but they have different perspectives.

Example

Suppose an order service consumes a payments service. The expected request is POST /payments with Content-Type: application/json and a body such as {"order_id":"ord_123","amount":4999,"currency":"USD"}.

The expected successful response is 201 Created with Content-Type: application/json and a body such as {"payment_id":"pay_456","status":"accepted"}.

The contract verifies that the payment service accepts this request and returns the required fields. If it changes the success status from 201 to 200, renames payment_id, or changes the currency representation, verification can fail before deployment.

The contract should remain focused on externally observable behavior. Over-specifying implementation details makes it brittle and can cause false failures.

Trade-offs and Limitations

  • Maintenance cost: Contracts must evolve as consumers and providers change.

  • False confidence: A contract proves only the interactions it covers, not the correctness of the entire business workflow.

  • Over-coupling: Excessive contract details can force consumers to depend on irrelevant implementation behavior.

  • Coordination cost: Provider and consumer teams still need compatible deployment and release processes.

  • Tooling complexity: Contract generation, broker storage, and CI integration require operational setup.

Contract testing is less valuable when an API is internal, has only one tightly coupled consumer, or changes so frequently that maintaining executable contracts costs more than the risk it mitigates. It is especially useful for public APIs, shared internal APIs, and independently deployed services.

Best Practices

  • Keep contracts minimal and behavior-focused.

  • Review changes to contracts with affected consumer teams.

  • Run provider verification in CI before deployment.

  • Include important error and authentication scenarios, not only the happy path.

  • Retain a smaller number of end-to-end tests for critical cross-service workflows.

  • Version contracts so consumers can detect breaking changes.

A common mistake is treating contract testing as a replacement for integration or end-to-end testing. Interviewers usually look for an explanation that it provides fast compatibility feedback at API boundaries, while broader system behavior still requires integration testing.

39

How do you mock APIs for development and testing?

API mocking replaces a real service or dependency with controlled responses so developers and tests can work independently of production infrastructure. It improves speed, determinism and fault simulation, but mocks can drift from the real API and conceal integration defects.

Read full answer

Applies toOpenAPI 3.1; mocking principles apply to all HTTP API versions

Why API Mocking Exists

API mocking solves several development and testing problems:

  • Frontend development: UI work can begin before the backend is deployed.

  • Independent testing: Tests do not depend on shared environments, data or network availability.

  • Failure simulation: Teams can reproduce timeouts, 429, 500 and malformed responses that are difficult to trigger reliably.

  • Controlled state: Responses can contain fixed IDs, timestamps and pagination results, making assertions repeatable.

  • Parallel delivery: Frontend, backend and contract-testing teams can progress concurrently.

For example, an e-commerce frontend can consume mocked POST /orders and GET /orders/{orderId} responses while the payment service is still being built.

Common Mocking Approaches

Approach How it works Best use Limitation
Static fixture Returns predefined JSON or XML Stable responses, simple unit tests Limited realism and scenario coverage
Dynamic mock server Generates responses from routes or an OpenAPI contract Developing several clients against one API More setup than static fixtures
Record and replay Captures real traffic and returns it later Reproducing production-like behavior Sensitive data and stale responses
Client interception Intercepts requests inside the client or test framework Browser and SDK tests Does not test real networking or deployment behavior
Service virtualization Simulates one or more downstream services Integration tests without real dependencies Operational and maintenance overhead

The related testing-double terms have slightly different meanings:

  • Stub: Returns a predefined response.

  • Fake: Provides a simplified but working implementation, such as an in-memory repository.

  • Mock: Verifies expected calls or interactions in addition to returning results.

  • Service virtualization: Emulates external systems and their protocols at a broader level.

Designing a Useful Mock Contract

The mock should represent the API contract, not just return a successful response.

  • Use the real contract: Derive paths, methods, schemas, status codes and validation rules from an OpenAPI 3.1 document where possible.

  • Model realistic errors: Include examples such as 400, 401, 403, 404, 409, 422 and 429.

  • Match authentication behavior: Simulate expired API keys, invalid OAuth 2.0 tokens and insufficient scopes without exposing real credentials.

  • Respect HTTP method semantics: PUT and DELETE are idempotent; POST is not inherently idempotent; PATCH is not guaranteed to be.

  • Support idempotency where defined: A POST endpoint that explicitly supports an Idempotency-Key can return the same logical result for retries using the same key and an identical request.

  • Keep data deterministic: Use predictable IDs, timestamps and ordering. Dynamically generated values should still be controlled by the test.

  • Exercise pagination and filtering: Return valid cursor or offset metadata and representative empty-page results.

  • Simulate latency and failures: Configurable delays and errors help test timeouts, retry policies and circuit breakers.

OpenAPI describes the interface, but it does not fully specify runtime behavior. Error handling, ordering, state transitions and side effects need explicit mock scenarios and contract tests.

Code Example

A frontend can develop against this contract:

POST /orders HTTP/1.1
Host: api.example.com
Content-Type: application/json
Content-Length: 71
Idempotency-Key: order-2025-00042

{"customerId":"cus_123","items":[{"productId":"sku_456","quantity":1}]}

A successful mock should mirror the intended create semantics:

HTTP/1.1 201 Created
Location: /orders/ord_789
Content-Type: application/json
Content-Length: 66

{"id":"ord_789","status":"pending_payment","customerId":"cus_123"}

A validation failure should use a structured error body:

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

{"type":"https://api.example.com/problems/insufficient-stock","title":"Insufficient stock","status":422,"detail":"sku_456 has only zero units available"}

The exact problem type URL depends on the API. The important point is that mocks should preserve the status, content type and error shape promised to consumers.

Best Practices and Pitfalls

  • Treat the contract as the source of truth: Generate or validate mocks against the current API specification.

  • Run real integration tests too: Mocks prove client behavior against an assumption; they do not prove that the deployed service behaves that way.

  • Detect drift in CI: Compare consumer expectations with the provider contract and run a small set of tests against a deployed environment.

  • Avoid sensitive recordings: Tokenize or synthesize customer data before storing captured responses.

  • Do not mock the code under test: Unit tests should call the real implementation while replacing only external dependencies.

  • Do not replace contract testing: Mocks cannot detect whether request serialization, headers or status handling match the real service.

  • Keep mocks deterministic: Random values and uncontrolled clock behavior create flaky tests.

  • Use mocks for boundaries, not everything: A database repository test may use a real temporary PostgreSQL instance when persistence semantics are important.

The common mistake is adding a mock layer without a drift-detection strategy. Interviewers usually look for awareness that mocks improve isolation but reduce confidence in end-to-end compatibility.

40

How does automated API testing improve the SDLC?

Automated API testing improves the software development lifecycle by executing repeatable checks against API contracts, dependencies, and workflows during coding, integration, deployment, and release. It provides faster feedback, catches regressions early, and enables teams to deploy changes more safely.

Read full answer

Applies toall versions

Why Automation Matters

Without automation, regression testing depends heavily on manual effort. Developers may verify the changed endpoint but overlook unintended effects on authentication, validation, pagination, error handling, or downstream services.

Automated API testing addresses this by:

  • Detecting defects early: Failed requests and incorrect responses are identified before code reaches production.

  • Providing fast feedback: Developers receive results within minutes rather than waiting for a manual regression cycle.

  • Ensuring compatibility: Contract tests can detect breaking changes before they affect other teams or clients.

  • Reducing regression risk: Existing behavior is tested whenever relevant code changes.

  • Supporting safe releases: Smoke and end-to-end tests can gate deployment to staging, canaries, or production.

  • Improving test coverage: Repetitive edge cases, such as invalid input and missing authentication, can be executed consistently.

  • Documenting behavior: Executable tests demonstrate how an endpoint is expected to behave.

For example, in an e-commerce system, an automated test can verify that creating an order returns 201 Created, persists the correct customer and items, and, if the API supports idempotency keys, does not create duplicates when the same key is submitted again.

Where It Fits in the SDLC

  1. During development: Developers run focused tests locally while changing handlers, serializers, or business logic.

  2. During pull requests: CI validates the API specification, formatting, schema compatibility, and functional behavior.

  3. During integration: Tests verify that the service works with its actual database, message broker, or external dependencies.

  4. Before deployment: Contract, regression, and smoke tests run against a production-like environment.

  5. After deployment: Health checks and smoke tests detect deployment failures, while synthetic transactions validate critical user journeys.

A typical CI pipeline runs OpenAPI validation → API linting → unit and component tests → contract tests → integration tests → end-to-end smoke tests → deployment approval.

Faster and more isolated checks should run before slower tests. This reduces feedback time and prevents expensive environments from being used for basic validation.

Example Test Flow

A client can submit POST /orders with an Authorization: Bearer <token> header, an Idempotency-Key: 7d42b071-8f36-4ca8-ae48-4c92e2cbe7b1 header, and a JSON body such as {"customerId":"cust_123","items":[{"sku":"book-001","quantity":2}]}.

The service can respond with 201 Created, a Location: /orders/ord_456 header, and a JSON body such as {"id":"ord_456","status":"pending","customerId":"cust_123","total":39.98,"currency":"USD"}.

An automated test can assert the status code, Location header, response schema, field values, authentication requirements, and database state. If the endpoint supports idempotency keys, it can repeat the request with the same key and verify that only one order was created. Negative cases can also verify that semantically invalid items produce 422 Unprocessable Entity, missing credentials produce 401 Unauthorized, and an authenticated user without permission receives 403 Forbidden.

Trade-offs and Limitations

  • Infrastructure cost: Integration tests require databases, containers, mocked dependencies, and test environments.

  • Maintenance effort: Tests must evolve as contracts and business rules change.

  • Flakiness: Timing-dependent assertions, unstable external services, and shared test data can produce false failures.

  • False confidence: Passing endpoint tests do not prove that the complete user experience works.

  • Coverage trade-off: Broad end-to-end suites are slower and harder to diagnose than focused tests.

  • Over-coupling: Tests that depend too heavily on internal implementation details become expensive to refactor.

Automation should not replace exploratory testing, usability assessment, or judgment about business risk. The objective is not maximum test count; it is dependable feedback at the right stage.

Best Practices and Interview Focus

  • Test behavior and contracts, not private implementation details.

  • Keep unit and component tests fast; reserve end-to-end tests for critical journeys.

  • Use deterministic test data and isolate concurrent tests.

  • Validate request and response schemas automatically.

  • Test error responses, authorization boundaries, retries, idempotency, and backward compatibility.

  • Quarantine flaky tests and fix their root cause rather than ignoring them.

  • Run deployment gates against production-like configurations, including authentication and network policies.

Interviewers typically look for a lifecycle-oriented answer rather than “it catches bugs.” A common mistake is proposing a large end-to-end suite without discussing speed, isolation, maintenance, or flaky tests. Strong candidates explain how automated API testing creates a fast feedback loop while balancing coverage, cost, and reliability.

41

How do you handle large API response datasets?

Handle large datasets by returning bounded, queryable pages instead of one unbounded collection. Cursor pagination, server-side filtering, limited fields, compression, streaming, and asynchronous exports each address different bandwidth, latency, memory, and database costs.

Read full answer

Applies toHTTP REST APIs over HTTP/1.1, HTTP/2, and HTTP/3

How It Works

The typical request flow is:

Client → API service → database query and filtering → page-size enforcement → serialization and compression → client

Without controls, a request such as GET /orders might load millions of rows into the service, serialize a large JSON document, and force the client to allocate substantial memory. This increases database load, response latency, network transfer time, and failure probability.

APIs should instead treat large collections as paginated resources and make the collection contract explicit: default page size, maximum page size, ordering, filters, cursor lifetime, and response metadata.

Pagination Trade-offs

Approach Advantages Costs and Limitations Best Use
Offset pagination Simple to implement; supports random page numbers Large offsets become slower; inserts or deletes can cause duplicates or skipped records Small, stable datasets or administrative APIs
Cursor pagination Efficient keyset queries; less sensitive to changes than offsets Cursor is opaque; users cannot jump directly to an arbitrary page Large, frequently changing datasets
Streaming Starts delivering data without constructing the entire response Requires backpressure and partial-failure handling; long-running connections Large sequential datasets that clients can process incrementally

Cursor pagination should use a deterministic ordering with a unique tie-breaker, such as created_at, id. Otherwise, records with identical timestamps can be skipped or repeated between pages.

Reducing Payload Size

  • Filter on the server: Support allowlisted query parameters such as status, created_after, and customer_id. Reject unsupported fields rather than passing arbitrary parameters to a database query.

  • Limit fields: Permit clients to request a small set of fields when supported. Avoid returning internal metadata, audit fields, or large nested objects by default.

  • Cap page size: A default such as 100 records with a documented maximum of 1,000 may be appropriate, but the values must match workload and database characteristics.

  • Compress responses: Brotli or gzip can substantially reduce JSON transfer size, usually at the cost of CPU and some latency. Compression does not reduce database work, server memory usage, or client parsing cost.

  • Avoid unnecessary counts: Returning total_count can require an expensive database count. Provide it only when clients genuinely need it, or estimate it separately.

  • Use caching carefully: Cache public or safely reusable pages with an explicit invalidation or TTL policy. Personalized pages should not leak between users.

Large Exports

For a moderately large but sequential result, streaming formats such as NDJSON can reduce memory usage. The server must support backpressure and define what happens when the connection or source database fails midway.

For multi-gigabyte exports, prefer an asynchronous workflow:

  1. The client submits an export request.

  2. The API creates a job and returns 202 Accepted.

  3. A worker queries the data and writes it to object storage.

  4. The client polls for status or receives a webhook.

  5. The API returns a short-lived, authorized download URL.

This avoids tying up web workers and improves failure isolation, but adds job state, storage, monitoring, cleanup, and duplicate-request handling. Use an idempotency key when creating export jobs.

Code Example

GET /orders?status=PAID&sort=created_at,id&limit=100&after=cursor_123 HTTP/1.1
Host: api.example.com
Accept: application/json
Accept-Encoding: br, gzip
Authorization: Bearer <token>
HTTP/1.1 200 OK
Content-Type: application/json
Content-Encoding: br
Cache-Control: private, max-age=30
Link: </orders?status=PAID&sort=created_at,id&limit=100&after=eyJpZCI6Im9yZF8xMjMifQ>; rel="next"

{
  "data": [
    {
      "id": "ord_123",
      "status": "PAID",
      "created_at": "2025-01-12T10:30:00Z",
      "total": 49.95
    }
  ],
  "pagination": {
    "limit": 100,
    "next_cursor": "eyJpZCI6Im9yZF8xMjMifQ"
  }
}

The cursor remains opaque: clients must send it back unchanged rather than constructing or interpreting it.

Best Practices and Common Pitfalls

  • Document default and maximum page sizes, supported filters, ordering rules, and cursor expiration.

  • Validate cursor and filter failures consistently; use 400 for malformed requests, 422 for semantically invalid filters, and 429 with Retry-After for rate limiting.

  • Test concurrent inserts, deletes, and updates around page boundaries.

  • Set limits at both the API and database layers so callers cannot bypass them.

  • Monitor p95 latency, response bytes, database time, cache hit rate, expired-cursor errors, and export-job failures.

  • Use idempotency keys for export creation and other non-idempotent operations.

The common mistake is relying only on compression or a nominally small page limit. The more important design decision is bounding work at the query and contract levels; otherwise, a single request can still consume excessive database, memory, and network resources.

42

How should an HTTP API support multiple response formats?

Content negotiation lets an HTTP API expose one logical resource in different representations, such as JSON or XML. The client requests a preferred format, while the server returns a compatible representation or an appropriate error.

Read full answer

Applies toHTTP/1.1, HTTP/2, and HTTP/3; OpenAPI 3.x for the documentation example

Design Model

The problem is that different clients need different representations: browser clients usually prefer JSON, reporting systems may need XML, and batch integrations may require CSV.

A typical design separates the resource from its representation:

  • Resource identity: /orders/123 identifies the order.

  • Requested representation: The client sends an Accept header.

  • Selected representation: The server chooses a supported media type and returns it in Content-Type.

  • Request payload format: The client uses Content-Type to describe the representation it sends in the request body.

For example:

GET /orders/123 HTTP/1.1
Host: api.example.com
Accept: application/json, application/xml;q=0.8

The q values express preference. A value of q=0 marks a format as unacceptable. If the client omits Accept or accepts any type with /, the server normally chooses its default representation, commonly JSON.

Supported Formats

A practical format policy might include:

  • JSON: A good default for general-purpose web APIs because it is widely supported, straightforward to consume, and compact when serialized without unnecessary whitespace.

  • XML: Useful when enterprise or legacy clients require it. Disable external entity resolution to reduce XXE risk.

  • CSV: Appropriate for exports and simple flat records, but unsuitable for nested resources or structured errors.

  • Problem details: Use application/problem+json or application/problem+xml for standardized error responses.

Keep one canonical internal order model and convert it through format-specific serializers. Otherwise, validation, pagination, and business rules can drift between implementations.

GraphQL and gRPC are not merely alternative serialization formats for a conventional REST endpoint. GraphQL usually returns JSON over HTTP, while gRPC defines its own contract and transport. They should normally be separate APIs rather than competing Accept formats on one resource.

Code Example

When JSON is selected:

HTTP/1.1 200 OK
Content-Type: application/json
Vary: Accept
Cache-Control: private, max-age=60

{
  "id": "123",
  "status": "shipped",
  "total": 49.95
}

When XML is selected:

HTTP/1.1 200 OK
Content-Type: application/xml; charset=utf-8
Vary: Accept
Cache-Control: private, max-age=60

<order>
  <id>123</id>
  <status>shipped</status>
  <total currency="USD">49.95</total>
</order>

The negotiation outcomes must be explicit:

  • 406 Not Acceptable: No requested representation is supported.

  • 415 Unsupported Media Type: The request body’s Content-Type is unsupported.

  • 400 Bad Request: The supplied representation is malformed or violates the basic request contract.

Vary: Accept is important because caches must distinguish responses produced for different Accept headers.

Trade-offs

  • Implementation complexity: Every supported format needs serialization, validation, error mapping, and contract tests.

  • Operational effort: Metrics and logs should record both the requested and selected media types without unnecessarily logging entire payloads.

  • Schema consistency: JSON, XML, and CSV expose different capabilities; flattening nested data or losing type information can create misleading clients.

  • Payload size: XML is often larger than JSON, while specialized binary formats may be more efficient but harder for general clients to inspect.

  • Caching behavior: Correct Vary handling is required, and some poorly designed caches can cache only one negotiated variant.

  • Security surface: Each parser has different risks; XML requires safe parser configuration, while JSON depth or payload limits may also be needed.

Do not add content negotiation when only one internal client exists or when every supported format has materially different semantics. Separate endpoints or a specialized API may then be clearer.

Best Practices

  • Document supported media types in OpenAPI 3.x, using multiple entries under each response object’s content map and request-body media types under requestBody.content.

  • Define one default representation and return it consistently when negotiation is absent or ambiguous.

  • Preserve the same resource semantics across formats; format-specific fields should be exceptional.

  • Keep API versioning separate from media-type versioning, such as application/vnd.example.order.v1+json.

  • Prefer Accept negotiation over query parameters such as ?format=json, because it uses HTTP’s standard negotiation mechanism and supports Vary: Accept; query parameters fragment the resource contract and introduce nonstandard format semantics.

  • Test exact, wildcard, absent, malformed, and unsupported Accept values.

  • Return structured errors using application/problem+json when possible.

Interviewers typically look for a distinction between resource identity, representation, and format negotiation, plus awareness of 406, 415, caching, and the maintenance cost of supporting several formats.

43

How should an API securely manage sensitive data throughout its lifecycle?

Sensitive-data management means minimizing sensitive data, protecting it in transit and at rest, and controlling access throughout collection, processing, storage, logging, sharing, and deletion. A secure API treats the entire data flow—not only the database—as one protection problem.

Read full answer

Applies toall HTTP API versions using TLS 1.2+ (prefer 1.3), HSTS (RFC 6797), OAuth 2.0 (RFC 6749) with PKCE (RFC 7636), and Problem Details (RFC 9457)

Minimize and Classify Data

Start with a data-flow inventory that includes APIs, databases, caches, logs, analytics, support tools, exports, backups, and third parties.

  • Classify data: Identify PII, credentials, payment-card data, health information, and business-sensitive records, then apply controls according to risk.

  • Collect only necessary fields: If country is sufficient, do not request a full address. Prefer provider tokens over raw payment-card numbers.

  • Return least data: Expose only fields the caller is authorized to receive; avoid returning complete database or customer objects by default.

  • Define lifecycle rules: Set retention and deletion periods for primary storage, replicas, caches, logs, analytics, exports, and backups.

Data minimization reduces breach impact and compliance exposure, but it can complicate workflows whose clients expect complete objects or historical records.

Protect Data in Transit, at Rest, and in Use

  • TLS: Require TLS 1.2 or 1.3 with strong cipher suites, prefer TLS 1.3, reject plaintext HTTP, and enable HSTS for browser-facing services.

  • Storage encryption: Encrypt databases, object storage, queues, and backups. Use managed key management, controlled key access, key versioning, and rotation rather than hard-coded keys.

  • Field-level encryption: Use AES-GCM with unique nonces where individual fields need independent protection. This sacrifices ordinary search, sorting, and aggregation, so apply it selectively.

  • Password storage: Use Argon2id, bcrypt, or scrypt with appropriate work factors. Encryption is reversible; password hashing is designed to be slow and salt-protected.

  • Tokenization: Replace highly sensitive values with tokens from a properly governed tokenization or payment provider.

  • Secrets management: Store API keys, signing keys, and database credentials in a secrets manager or KMS, not source code, images, or committed configuration.

Encryption and centralized key management add latency, cost, and operational dependencies. Design for high availability, and fail closed when authorization or required key access cannot be established safely.

Authenticate and Authorize Every Request

  • API keys: Use them to identify server-to-server clients; scope, rotate, and revoke them, and send them in the Authorization header rather than a URL.

  • OAuth 2.0: Use bearer access tokens for delegated user or organizational access. For JWT access tokens, validate the signature, issuer, audience, expiry, and relevant scopes; use PKCE for authorization-code public clients.

  • Object-level authorization: Verify access to the specific order, invoice, or patient record rather than relying only on a broad scope.

  • Least privilege: Restrict service accounts and tokens to required operations and resources. Require step-up authentication for exports, credential rotation, or bulk access.

  • Correct errors: Return 401 Unauthorized for missing or invalid authentication and 403 Forbidden for an authenticated caller lacking permission.

Authentication establishes identity; authorization controls access to each resource. Neither replaces minimization or secure downstream storage.

Design Leak-Resistant API Behavior

  • Use bodies for sensitive values: Prefer POST or PATCH bodies because URLs persist in logs and monitoring systems. Disable request-body logging by default.

  • Control caching: Use Cache-Control: no-store for sensitive responses and prevent inappropriate CDN or reverse-proxy caching.

  • Use safe errors: Return application/problem+json without stack traces, SQL fragments, internal identifiers, or submitted secrets.

  • Validate and limit: Use schemas, parameterized queries, per-client rate limits, and 429 Too Many Requests with Retry-After. Distinguish malformed requests (400) from well-formed but semantically invalid requests (422), and use 409 for conflicting operations such as reusing an idempotency key with a different payload.

  • Apply HTTP semantics: PUT and DELETE are idempotent; POST is not; PATCH is not guaranteed to be. Use 204 only for a successful response with no body. For retryable POST operations, accept a random, client-scoped idempotency key and return the original result for a matching retry.

Example request: POST /v1/customers with Content-Type: application/json and body {"email":"alice@example.com","name":"Alice Example"}. Example response: 201 Created, Location: /v1/customers/cus_123, Cache-Control: no-store, and body {"id":"cus_123","status":"active"}.

Operate and Audit the Lifecycle

  • Log minimally: Never log authorization headers, credentials, cookies, full request bodies, or raw sensitive fields by default.

  • Audit safely: Record the authenticated principal, action, resource reference, decision, timestamp, and correlation ID without reproducing the sensitive value. Store important records in append-only or tamper-resistant systems.

  • Monitor abuse: Alert on unusual export volume, repeated authorization failures, privilege changes, and suspicious access patterns.

  • Delete deliberately: Remove data from replicas, indexes, caches, and exports according to policy. For backups, use expiration or approved cryptographic-erasure procedures where appropriate.

  • Map dependencies: Include analytics, support tools, processors, and other third parties in the data-flow map; upstream encryption does not protect data after disclosure.

Trade-offs and Best Practices

Prioritize data-flow inventory, minimization, authorization, logging controls, and encryption according to risk. The common mistake is “encrypt everything” without defining plaintext access, key rotation, retention, or search requirements.

  • Field-level encryption improves confidentiality but weakens queryability.

  • Tokenization reduces exposure but creates provider and availability dependencies.

  • no-store protects sensitive responses but sacrifices caching benefits.

  • Immutable auditing improves investigations but increases storage cost.

  • Step-up authentication improves assurance but adds user friction.

Omit unnecessary data rather than encrypting it, and use field encryption or tokenization only when their operational costs are justified.

44

How should an API design filtering, sorting, and result ordering?

Filtering, sorting, and deterministic ordering should be explicit, validated parts of the API contract. Filtering narrows a resource collection, sorting defines the order of matching resources, and a unique tie-breaker makes that order stable across requests.

Read full answer

Applies toHTTP/1.1, HTTP/2, and HTTP/3 API contracts

How It Works

  • Filtering: Use query parameters with a documented syntax, such as status=paid, created_at_after=2026-01-01T00:00:00Z, or customer_id=123. Define boundary semantics precisely—for example, created_at_after is exclusive—and document accepted date and numeric formats.

  • Sorting: Use a sort parameter containing one or more fields and directions, for example sort=-created_at,id. Support only an allowlist of sortable fields and document that an omitted direction means ascending.

  • Deterministic order: Always include a unique tie-breaker such as id. Without it, records with equal sort values may appear in different orders between requests.

  • Default ordering: Define a default when sort is absent, such as newest resources first, and make that default part of the API contract.

  • Pagination: Combine filtering and sorting with pagination so clients can retrieve a bounded result set.

Keep parameter names and field semantics stable. For example, document whether status=paid means exactly paid, and whether date boundaries are inclusive.

Filtering Trade-Offs

Flexible filters improve client convenience but introduce several costs:

  • Performance: Complex predicates may require many indexes or expensive database scans.

  • Indexability: Arbitrary filters on rarely queried fields are difficult to optimize.

  • Security: Never interpolate user-provided field names or expressions into SQL. Map public names to server-controlled queries.

  • Complexity: A growing query language creates more validation, documentation, and testing work.

Use an allowlist and reject unknown fields. Prefer a small set of query operators, such as equality, range comparisons, inclusion, and existence. Do not expose a general expression language unless clients genuinely need one and the server can validate and resource-limit it safely.

A composite index may help when its column order matches common filter and sort patterns. For example, an orders table queried by status and ordered by created_at might benefit from an index beginning with status and followed by created_at and the tie-breaker. Exact index design depends on query frequency, selectivity, sort direction, and database behavior.

Sorting and Pagination

Approach Advantages Costs and Limitations
Offset pagination Easy URLs and direct navigation to a page number Large offsets require scanning or discarding preceding rows; inserts and deletes can shift page boundaries
Cursor-based keyset pagination Avoids offset page-shift problems and performs well for large or changing collections Cursors are opaque, arbitrary page jumps are awkward, and consistency depends on the ordering keys and concurrent changes

A cursor is the client-facing token, while keyset pagination is the query strategy that finds rows after the last returned sort tuple. A robust implementation stores every field in the effective ordering, including the tie-breaker, and selects the next rows using the last tuple.

Avoid promising that the same cursor returns identical results forever: concurrent updates or deletions can still affect records. Immutable, unique sort keys make this safer. If strict snapshot semantics are required, state that explicitly and consider a transaction or materialized snapshot, which adds operational and consistency costs. Use offset pagination when clients need numbered or arbitrary page navigation on a relatively small, stable collection.

Validation and Errors

  • Malformed syntax or values: Return 400 Bad Request when a parameter cannot be parsed or contains an invalid date, number, or enumeration value.

  • Invalid field or unsupported operator: Return 422 Unprocessable Content when the syntax is valid but the requested operation is not supported.

  • Unauthorized field access: Usually return 404 Not Found or 403 Forbidden, according to the API’s resource-disclosure policy.

  • Invalid pagination combination: Return 400 or 422 with a structured error body.

Document maximum limits, allowed operators, date formats, and behavior for empty or contradictory filters.

Example Request and Response

For example, GET /orders?status=paid&created_at_after=2026-01-01T00:00:00Z&sort=-created_at,id&limit=50 can return 200 OK with Content-Type: application/json and a body such as {"items":[{"id":"ord_8472","status":"paid","created_at":"2026-02-10T14:30:00Z"}],"next_cursor":"eyJjcmVhdGVkX2F0IjoiMjAyNi0wMi0xMFQxNDozMDowMFoiLCJpZCI6Im9yZF84NDcyIn0","limit":50}.

The cursor is opaque to clients. The server must validate and decode it rather than trusting its contents, and it should be scoped to the applicable filters and authorization context to prevent misuse.

Best Practices and Common Pitfalls

  • Allowlist fields: Validate filter and sort names against server-owned metadata.

  • Use explicit types: Parse dates as ISO 8601 timestamps, require integer identifiers, and enforce minimum and maximum numeric limits.

  • Bound the work: Apply result limits and query-complexity limits.

  • Optimize with real queries: Use database execution plans rather than assuming an index is effective.

  • Keep ordering stable: Include a unique tie-breaker and use the complete effective ordering in cursor pagination.

  • Avoid exposing database syntax: Do not accept raw SQL fragments or unvalidated column names.

  • Test the contract: Cover malformed parameters, unknown fields, empty results, duplicate sort values, and concurrent writes.

A common mistake is implementing flexible filtering while overlooking index coverage and pagination consistency. Interviewers often look for whether the candidate can connect query semantics to both client usability and database cost.

45

How do you manage database transactions in API endpoints?

Transaction management in an API endpoint defines which state changes are atomic, how concurrent requests are coordinated, and how failures or retries are handled. For a single database, use a short local transaction; for operations spanning multiple services, use patterns such as saga and transactional outbox instead of relying on one distributed database transaction.

Read full answer

Applies toHTTP/1.1 and HTTP/2; database-specific behavior varies

Transaction Boundaries

A transaction should represent one business operation, not necessarily one HTTP endpoint. Most of the time, a request maps cleanly to one database transaction:

  1. Authenticate and authorize the caller.

  2. Validate and normalize the input.

  3. Begin the database transaction.

  4. Read or lock the required records.

  5. Perform all related writes.

  6. Commit the transaction.

  7. Return the success response.

Keep transactions short because long-running transactions retain locks, consume pooled connections, increase contention, and make failures more expensive. Avoid network calls, message publishing, and other external I/O while locks are held.

A useful rule is: commit before sending a successful response. If the database commit succeeds but the response is lost, the client may retry; an idempotency mechanism is then needed to prevent duplicate effects.

Common Strategies

Strategy Use case Trade-off
Local database transaction Changes within one SQL database Strong atomicity, but no protection across services
Idempotency key Safe handling of retried POST requests Requires durable request and result storage
Optimistic concurrency Frequently updated records with low contention May fail under contention and require retries
Pessimistic locking Critical updates where failures are unacceptable Reduces concurrency and can cause deadlocks
Saga Workflow spanning multiple services or databases Eventual consistency and compensating logic
Transactional outbox Publishing events after a database change Adds an outbox table and background publisher

PUT and DELETE are HTTP idempotent methods, while POST is not. PATCH is not guaranteed to be idempotent. A well-designed endpoint should still enforce business-level idempotency where duplicate operations would cause harm.

Failure, Retry, and Idempotency Handling

The endpoint must define what happens at each failure point:

  • Validation failure: reject before committing, typically with 400 for malformed syntax or 422 for semantically invalid input.

  • Business conflict: return 409 Conflict.

  • Concurrent modification: return 409, or retry internally when the operation is safe to repeat.

  • Database or dependency failure: roll back and return 500 or 503.

  • Unknown commit outcome: resolve the outcome using an idempotency record rather than blindly repeating the write.

Retries should use exponential backoff with jitter and only occur when the operation is idempotent. A deadlock usually aborts the affected transaction, so the entire transaction must be replayed with bounded retries and jitter to avoid retry storms.

For a retried creation request, store the idempotency key, authenticated caller, operation, normalized request hash, processing state, and final response. Ideally, insert the idempotency record in the same database transaction as the business changes.

  • The same key with the same payload should return the original result.

  • The same key with a different payload should return 409.

  • Concurrent requests using the same key must not both perform the business operation.

  • A rolled-back transaction removes a same-transaction idempotency record automatically; retain failures separately only when the business policy requires it.

This solves the “database committed, response was lost” problem without making POST globally idempotent by definition.

Cross-Service Transactions

A database transaction cannot safely span remote services merely because an endpoint called them. Each service may own a separate database, and network failures create partial completion.

Use a saga when the workflow can be expressed as ordered steps with compensation. Use the transactional outbox when a local database change must reliably trigger an event: write the business state and outbox record atomically, then publish asynchronously. Two-phase commit can provide stronger coordination but introduces blocking, operational complexity, and poor failure characteristics; many high-volume service designs avoid it.

Code Example

For an order endpoint, write the idempotency record and order in one local transaction, commit the transaction, and only then send the 201 response. A retry with the same key and payload returns the stored result; reuse with a different payload returns 409.

POST /orders HTTP/1.1
Content-Type: application/json
Idempotency-Key: 54f09d3a-71d8-4b64-a41f-981bd4f76c91

{
  "customer_id": "cus_123",
  "items": [
    {"sku": "book-42", "quantity": 1}
  ]
}
HTTP/1.1 201 Created
Content-Type: application/json
Location: /orders/ord_789

{
  "id": "ord_789",
  "status": "pending"
}

A conflicting reuse can use the standard error media type:

HTTP/1.1 409 Conflict
Content-Type: application/problem+json

{
  "type": "https://api.example.com/problems/idempotency-conflict",
  "title": "Idempotency key conflict",
  "status": 409,
  "detail": "The key was already used with a different request payload."
}

Best Practices and Common Pitfalls

  • Keep transaction boundaries explicit and as small as practical.

  • Enforce invariants with database constraints as well as application validation.

  • Use optimistic version checks or conditional requests for lost-update protection.

  • Use a consistent lock order to reduce deadlocks.

  • Make error responses stable and machine-readable, preferably application/problem+json.

  • Monitor transaction duration, rollback rate, deadlock rate, pool saturation, and idempotency conflicts.

  • Do not assume a database rollback reverses external effects such as emails, payments, or published events.

A common interview mistake is describing an endpoint as “transactional” without explaining retries, partial failures, concurrent updates, or whether external side effects participate in the same atomic boundary.

46

Which API specification formats are useful, and what benefits do they provide?

An API specification is a machine-readable contract describing an API’s resources, operations, data types, errors, and constraints. Formats such as OpenAPI, JSON Schema, AsyncAPI, GraphQL SDL, and Protocol Buffers let teams agree on a contract before implementation and automate documentation, validation, compatibility checks, and code generation.

Read full answer

Applies toOpenAPI 3.1, JSON Schema 2020-12, AsyncAPI 3.0, GraphQL SDL, and Protocol Buffers

Problem the Specification Solves

Without an explicit contract, API producers and consumers often depend on informal communication, handwritten documentation, or implementation details. This leads to:

  • Contract drift: A field, endpoint, or status code changes without consumers being notified.

  • Integration delays: Client teams must wait for an implementation or guess its behavior.

  • Inconsistent validation and errors: Different operations accept or reject similar payloads in different ways.

  • Slow onboarding: Developers reverse-engineer behavior from production code.

  • Unsafe changes: A seemingly small modification breaks existing clients.

A specification provides a shared source of truth that teams can review, test, and automate against. It describes the expected contract, but it does not by itself prove that an implementation conforms to that contract or is secure.

Common API Specification Formats

Format Best suited for Main benefit
OpenAPI 3.1 HTTP REST APIs Describes paths, methods, parameters, request bodies, responses, security requirements, and schemas in YAML or JSON; its schema vocabulary aligns with JSON Schema 2020-12
JSON Schema 2020-12 Data validation and event payloads Defines JSON structure, required fields, types, ranges, and other constraints independently of any transport protocol
AsyncAPI 3.0 Event-driven APIs Describes channels, messages, producers, consumers, and asynchronous interactions
GraphQL SDL GraphQL APIs Defines a type system and the available queries, mutations, subscriptions, and custom directives
Protocol Buffers RPC and strongly typed service contracts Defines messages and service interfaces while supporting compact binary serialization and code generation

These formats cover different layers. OpenAPI models an HTTP interface, JSON Schema validates data, AsyncAPI models event channels, GraphQL SDL describes a GraphQL type system, and Protocol Buffers can define both service interfaces and wire messages.

Benefits

  • Machine-readable contract: Tools can analyze the specification rather than relying only on prose.

  • Generated documentation: Reference documentation can be produced directly from the contract.

  • Client and server generation: SDKs, models, and request helpers can be generated for supported languages.

  • Early validation: JSON Schema constraints can reject malformed request or event payloads before processing.

  • Contract testing: Expected requests and responses can be verified against the running service.

  • Compatibility checks: CI can identify removed fields, changed types, or altered operations before deployment.

  • Governance: Teams can enforce naming, authentication, pagination, and error-response conventions.

  • Better onboarding: Consumers can understand operations and payload shapes from one reviewed artifact.

For example, an order API can specify POST /orders, accept the JSON body {"sku":"SKU-123","quantity":2}, and return 201 Created with a Location header and the JSON response {"id":"ord_42","sku":"SKU-123","quantity":2,"status":"created"}. OpenAPI can represent that contract directly, while JSON Schema can validate the request and response structures.

Trade-offs and Limitations

  • Maintenance cost: Specifications become stale unless CI checks them against the implementation.

  • False confidence: A valid specification does not prove that server behavior, security, or performance is correct.

  • Tool limitations: Generators may produce rigid models, incomplete clients, or unnecessary dependencies.

  • Governance overhead: Large APIs need ownership, review rules, versioning policies, and automated checks.

  • Over-engineering: A small internal API used by one tightly coupled team may need only a lightweight contract.

  • Competing sources of truth: Combining several specifications and custom conventions can create consistency problems.

  • Vendor and ecosystem effects: Some tools support only selected specification versions or extensions.

Do not introduce a specification format merely because it is popular. It is most useful when independent consumers, multiple teams, validation, code generation, or formal lifecycle management justify the operational cost.

Best Practices and Interview Tips

  • Store the specification in version control and review changes like production code.

  • Validate it with format-specific tooling in CI, then test the running service for conformance.

  • Document HTTP semantics accurately: PUT and DELETE are idempotent, POST is not, and PATCH is not guaranteed to be idempotent.

  • Use plural resource names such as /orders, suitable methods, and accurate statuses such as 201, 400, 409, and 429.

  • Prefer additive, backward-compatible changes and document deprecation before removing fields or operations.

  • Define stable error responses, commonly using application/problem+json.

  • Generate clients where useful, but review and test generated artifacts.

Interviewers usually look for the distinction between an API style, such as REST, and an API specification format, such as OpenAPI. A common mistake is claiming that a specification validates a running service by itself; conformance requires separate tooling or contract tests.

47

How do you design an API that follows industry standards?

An industry-standard API design uses resource-oriented contracts, correct HTTP semantics, machine-readable documentation, and predictable error handling. The goal is not merely to expose endpoints, but to create a contract that other teams can adopt without guessing how requests, responses, authentication, pagination, or failures behave.

Read full answer

Applies toall versions

Start with the Problem

Before choosing URLs or methods, identify:

  • Functional requirements: What resources do clients create, retrieve, modify, or delete?

  • Non-functional requirements: Expected traffic, latency, availability, data consistency, and regional reach.

  • Consumers: Public clients, internal services, mobile applications, or partner integrations.

  • Security boundaries: User identity, tenant isolation, permissions, sensitive fields, and audit requirements.

  • Lifecycle needs: Compatibility guarantees, deprecation policy, migration support, and ownership.

For example, an e-commerce checkout API might support creating an order, changing its shipping address, authorizing payment, and querying its status. Each operation has different consistency, idempotency, and failure requirements.

Model the HTTP Contract

Use plural nouns for resource collections and stable identifiers for individual resources:

  • POST /v1/orders

  • GET /v1/orders/{orderId}

  • PUT /v1/orders/{orderId}

  • PATCH /v1/orders/{orderId}

  • DELETE /v1/orders/{orderId}

Method Safe Idempotent Typical use
GET Yes Yes Read a resource
POST No No Create a resource or trigger processing
PUT No Yes Replace a resource with a complete representation
DELETE No Yes Remove a resource
PATCH No Not guaranteed Apply a partial update

Use status codes consistently:

  • 201 Created: Resource created; include a Location header.

  • 200 OK: Successful response containing a representation.

  • 204 No Content: Successful operation with no response body.

  • 400 Bad Request: Malformed request syntax or invalid framing.

  • 401 Unauthorized: Authentication is missing or invalid.

  • 403 Forbidden: Authenticated identity lacks permission.

  • 404 Not Found: Resource is unavailable or hidden by authorization rules.

  • 409 Conflict: Current resource state conflicts with the request.

  • 422 Unprocessable Content: Syntactically valid request fails semantic validation.

  • 429 Too Many Requests: Rate limit exceeded; normally include Retry-After.

Avoid verbs in resource paths when standard methods already express the action. Use a subordinate action only for domain operations that do not naturally map to CRUD, such as POST /v1/orders/{orderId}/cancellations.

Define Errors, Security, and Versioning

Use application/problem+json for standardized errors, based on RFC 9457. Every error should include a stable machine-readable type, human-readable title, numeric status, request-specific detail, and optionally field-level validation errors.

For authentication and authorization:

  • Use API keys for server-to-server identification when narrowly scoped.

  • Use OAuth 2.0 when delegated access to user resources is required.

  • Use short-lived JWT access tokens with audience, issuer, and expiration validation.

  • Enforce authorization on every operation; never rely on a hidden UI control.

Prefer additive, backward-compatible changes. Introduce a major version such as /v1 for breaking changes, publish a migration guide, and provide an observable deprecation period. Document the contract in OpenAPI 3.1 and validate implementations against it in CI.

Design Operational Behavior

  • Pagination: Prefer cursor pagination for large or frequently changing collections; offset pagination is simpler but becomes expensive at deep offsets and can produce duplicates or omissions when records are inserted.

  • Filtering and sorting: Allowlist supported fields to prevent arbitrary, expensive queries.

  • Rate limiting: Return 429 and document the quota, Retry-After, and whether headers such as X-RateLimit-Remaining are available.

  • Idempotency: For retryable creation requests, accept an Idempotency-Key. Compute and store a fingerprint of the request alongside the original result for a defined period. If the same key is reused with a different payload, reject it with 409 Conflict. On a safe retry with the identical payload, return the original stored result without creating a duplicate resource.

  • Webhooks: Use POST, require signatures, include event IDs, define retry schedules, and make consumers deduplicate events.

  • Concurrency: Expose ETag values for optimistic concurrency when simultaneous edits matter.

Code Example

A successful order creation:

POST /v1/orders HTTP/1.1
Host: api.example.com
Content-Type: application/json
Idempotency-Key: 8f2c4e15-3f3b-4fd4-9ca8-71d77a2317b9

{
  "customerId": "cus_123",
  "items": [
    { "sku": "SKU-42", "quantity": 2 }
  ]
}
HTTP/1.1 201 Created
Content-Type: application/json
Location: /v1/orders/ord_789

{
  "id": "ord_789",
  "status": "pending_payment",
  "customerId": "cus_123"
}

A validation failure:

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

{
  "type": "/problems/validation-error",
  "title": "Request validation failed",
  "status": 422,
  "detail": "The order contains an invalid item.",
  "errors": [
    {
      "field": "items[0].quantity",
      "reason": "Must be greater than zero."
    }
  ]
}

Trade-offs and Common Mistakes

  • REST: Strong default for public, resource-oriented APIs. Choose it when you want wide compatibility with HTTP caches, browsers, and existing tooling.

  • GraphQL: Can reduce over-fetching for highly connected client views, but adds query-cost control, complexity, and governance overhead.

  • gRPC: Efficient and strongly typed for internal service-to-service communication, but less convenient for browser clients and ad-hoc public debugging.

The most common mistake is treating an API as a list of URLs without defining its operational contract. Interviewers usually look for explicit trade-offs, consistent HTTP semantics, idempotency, versioning, error handling, and a plan for how clients evolve safely.

48

How will OpenAPI/Swagger specifications evolve and affect API design?

OpenAPI will likely evolve from a documentation format into a more executable, versioned contract for APIs, events, and generated tooling. Swagger remains the associated tooling ecosystem, so its impact comes from how consistently teams define, validate, test, and evolve contracts—not from the specification alone.

Read full answer

Applies toOpenAPI 3.2.0, with OpenAPI 3.1.x as a widely supported baseline; Swagger tools that explicitly support the selected version

Expected Evolution

Area Likely direction Effect on API design
Schema semantics Stronger alignment with JSON Schema and Web-platform types More expressive request and response models
Event-driven APIs Better support for webhooks, callbacks, and integration with specifications such as AsyncAPI HTTP APIs and asynchronous event contracts become more closely related
Lifecycle management Better breaking-change detection, linting, and contract-testing integrations Teams can detect incompatible changes before deployment
Security More complete representations of OAuth 2.0, API keys, mutual TLS, and related schemes Authentication requirements become visible and testable
Automation Improved mock generation, SDK generation, documentation, and policy enforcement OpenAPI increasingly influences implementation, not just documentation

The distinction between specifications and tools matters: OpenAPI is the specification, while Swagger Editor, Swagger UI, validators, and generators are tools built around it. Tool support may lag a new OpenAPI release, so teams should select a version supported by their validation and CI pipeline.

Impact on API Design

  • Explicit contracts: Operations, parameters, schemas, status codes, authentication, and errors become reviewable before implementation.

  • Consistent resource design: OpenAPI encourages plural resource names, predictable HTTP semantics, and uniform pagination, filtering, and error formats.

  • Correct HTTP behavior: GET and HEAD are safe; PUT and DELETE are idempotent; POST is not; PATCH is not guaranteed to be.

  • Standard status codes: Use 201 for creation, 204 for an empty successful response, 400 for malformed syntax, 422 for syntactically valid but semantically invalid input, 401 for missing or invalid authentication, 403 for insufficient authorization, 409 for state conflicts, and 429 for rate limiting.

  • Shared error models: application/problem+json based on RFC 9457 provides a consistent structure for machine-readable failures.

  • Generated artifacts: SDKs, mocks, documentation, and tests can start from the specification, reducing duplicated interpretation.

OpenAPI does not determine whether a business model is sensible, whether an API is truly idempotent, or whether the implementation matches the contract. Runtime request validation and contract tests remain necessary.

Evolution and Compatibility

Prefer additive changes and deprecate old fields or operations before removing them. Common breaking changes include adding a required request field, narrowing accepted input, changing a type or format, removing an operation, or adding an enum value that existing clients do not understand.

The openapi field identifies the specification version, while info.version identifies the API contract version. They are separate concepts. Major API versions should represent intentional breaking releases rather than being used for every small change.

A CI pipeline can validate the document, detect differences from the previous version, and run consumer-contract tests. Tools such as oasdiff can help identify likely incompatibilities, but reviewers must still understand the API’s business semantics.

Practical API Example

An order-creation contract can require an Idempotency-Key header, a JSON request body, a 201 Created response with a Location header, and application/problem+json errors.

For example, POST /orders with Content-Type: application/json, a unique Idempotency-Key, and body {"sku":"SKU-123","quantity":2} can return 201 Created with {"id":"b6d4f1b0-7f27-4e5d-90ae-4c8bb6f97032","status":"created"}. Reusing the key with a different payload can return 409 Conflict with {"type":"https://api.example.com/problems/idempotency-conflict","title":"Idempotency conflict","status":409}.

The POST operation remains non-idempotent under HTTP semantics; the idempotency guarantee comes from the server recognizing the key and returning the result of the original request for a repeated identical request.

Best Practices and Trade-offs

  • Use contract-first design for public APIs and APIs consumed by independently deployed teams.

  • Lint and diff specifications in CI, then supplement this with runtime validation and consumer-contract tests.

  • Keep generated SDKs behind controlled publishing so generated code is reviewed and tested.

  • Do not assume a valid specification means the server behaves correctly.

  • Maintain ownership of schemas and versioning; otherwise the specification becomes documentation that drifts from reality.

  • Use AsyncAPI when event streams and brokers are the primary contract rather than treating an HTTP OpenAPI document as an event-modeling tool.

The main cost is governance: teams must review schemas, resolve compatibility issues, and keep specifications synchronized with implementations. OpenAPI pays off most when several consumers depend on a stable contract; for a small, internal, rapidly changing interface, a lightweight specification may provide more value than a full toolchain.

49

How do you design interoperable APIs for third-party clients?

Interoperability means third-party clients can integrate through shared standards, predictable semantics, and a documented contract rather than provider-specific knowledge. A stable API defines resources, errors, authentication, compatibility rules, and HTTP behavior so clients can evolve independently.

Read full answer

Applies toHTTP/1.1 and HTTP/2 APIs with JSON and OpenAPI 3.1

Core Contract and API Style

Third-party clients need one predictable contract; otherwise every integration rediscovers hidden conventions.

  • Resources: Use stable plural nouns and opaque identifiers, for example /v1/orders and /v1/orders/{orderId}.

  • Methods: GET is safe; POST is not inherently idempotent; PUT and DELETE are idempotent; PATCH is not guaranteed to be.

  • Payloads: Prefer JSON with application/json; define required, optional, and nullable fields, enums, timestamps using RFC 3339, and explicit units such as timeoutMs.

  • Contract: Publish request and response schemas, error formats, authentication requirements, pagination, and compatibility policies.

Style Main benefit Main trade-off
REST with JSON Broad HTTP interoperability and potential HTTP caching Requires disciplined schemas and documentation
GraphQL Clients request tailored fields through a typed schema More complex gateway, caching, and authorization behavior
Protobuf over gRPC Typed contracts and efficient binary payloads Browser, proxy, and debugging constraints

For a public API serving heterogeneous clients, REST with JSON is the safest default. Use GraphQL when clients need highly variable queries, and gRPC for controlled integrations where both sides support HTTP/2 and Protobuf tooling.

Errors, Pagination, and Filtering

Use a consistent error envelope so clients can react programmatically rather than parse prose. For example, a payment API should distinguish malformed input, failed business rules, duplicates, and throttling.

Situation Typical status
Malformed syntax or invalid parameters 400 Bad Request
Semantically invalid request 422 Unprocessable Content
Missing or invalid credentials 401 Unauthorized
Valid credentials without sufficient permission 403 Forbidden
Duplicate or conflicting state 409 Conflict
Rate limit exceeded 429 Too Many Requests
Successful empty response 204 No Content

RFC 9457 Problem Details provides a standard JSON representation for errors.

  • Offset pagination: Simple and supports direct page navigation, but large offsets can be slow and results can shift between pages.

  • Cursor pagination: More stable for large or changing datasets, but cursors must be opaque and clients cannot easily jump to arbitrary pages.

Filtering and sorting should use documented query parameters and deterministic defaults. Apply pagination and result limits to protect backend capacity.

Authentication, Idempotency, and Webhooks

Use TLS 1.2 or later, preferably TLS 1.3. API keys identify a client or project. OAuth 2.0 supports delegated user authorization and can use client credentials for machine-to-machine access. A JWT is a token format, not an authorization protocol; opaque OAuth tokens are also valid.

For unsafe operations, support an Idempotency-Key header when clients may retry. Scope keys to the authenticated client and operation, and store the completed result. The same key and payload should return the original result; the same key with a different payload should return 409 Conflict.

For webhooks:

  • Include a unique event ID and versioned event type.

  • Sign the payload, for example with HMAC-SHA-256, and include a timestamp to detect replay.

  • Document the retry schedule and timeout behavior.

  • Assume retries can duplicate events, so clients should deduplicate by event ID.

  • Do not assume events arrive in order; include ordering data or require clients to retrieve current state.

Also define rate limits and Retry-After, token scopes and permission checks, request and response size limits, timeout behavior, and partial-failure semantics.

Code Example

A predictable order-creation endpoint should expose a stable resource, an idempotency key, and a standard error format.

POST /v1/orders HTTP/1.1
Host: api.example.com
Authorization: Bearer <access-token>
Content-Type: application/json
Idempotency-Key: 7c9e6679-7425-40de-944b-e07fc1f90ae7

{
  "customerId": "cus_123",
  "items": [
    { "sku": "book-001", "quantity": 2 }
  ]
}
HTTP/1.1 201 Created
Location: /v1/orders/ord_456
Content-Type: application/json

{
  "id": "ord_456",
  "status": "pending",
  "createdAt": "2025-03-08T10:15:30Z"
}

If the SKU is unknown, return a consistent Problem Details response:

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

{
  "type": "https://api.example.com/problems/unknown-sku",
  "title": "Unknown SKU",
  "status": 422,
  "detail": "The requested SKU does not exist.",
  "instance": "/v1/orders"
}

Evolution, Compatibility, and Trade-offs

Publish a machine-readable OpenAPI 3.1 contract, generate documentation from it, and run consumer-driven contract tests. Prefer additive changes when clients are documented to ignore unknown response fields. Version only when a required change is genuinely breaking; a major version such as /v2/orders is clearer than silently changing the contract.

Removing a field, narrowing accepted values, changing units, or changing error semantics normally breaks existing clients even if the HTTP status remains unchanged.

Interoperability has costs: stricter contracts require validation and coordination, versioning adds operational complexity, and OAuth or webhook security adds implementation effort. Do not over-version small internal APIs; use consistent conventions, explicit ownership, and automated compatibility tests instead. The common interview mistake is designing attractive endpoints without defining error behavior, authorization, pagination, and backward-compatibility rules—the parts clients actually depend on.

50

How does JSON:API shape structured API response payloads?

JSON:API defines a predictable structure for API documents in which primary data, errors, metadata, links, and related resources have consistent top-level positions. It standardizes resource representation and relationships, but it does not replace HTTP semantics such as status codes, methods, or headers.

Read full answer

Applies toJSON:API 1.1

Top-Level Document Shape

A JSON:API document is a JSON object that must contain at least one of these top-level members:

  • data: The primary data, represented as one resource object, an array of resource objects, or null.

  • errors: An array of error objects describing one or more failures.

  • meta: A non-resource metadata object, such as request IDs, pagination counts, or audit information.

A document may also contain:

  • jsonapi: An object describing the server’s implementation, with optional version, ext, profile, and meta members.

  • links: An object containing links such as self, pagination links, or related-resource links.

  • included: An array containing full resource objects related to the primary data.

data and errors must not appear together. This separation gives clients an unambiguous rule for distinguishing successful resource responses from failure responses.

Resources and Relationships

Every resource object contains these members:

  • id: A non-empty string identifying the resource within its type. It may be omitted when the client creates a new resource; a local lid can identify it within the document instead.

  • type: A non-empty string identifying the resource type, such as articles. The specification allows plural or singular names; choose one convention and apply it consistently.

A resource object may also contain:

  • attributes: An object containing the resource’s ordinary fields.

  • relationships: An object describing links to other resources.

A relationship object can contain links, meta, and data. Its data member contains resource linkage—an identifier such as {"type":"people","id":"42"}—rather than embedding the complete related resource. It can also be null or an array for to-many relationships.

The top-level included array can contain full related resources requested with a query such as ?include=author. Each included resource must be reachable from the primary data through a relationship chain. A compound document must not include more than one resource object for the same type and id pair.

Errors and Extensions

An error response uses a top-level errors array. Error objects can contain:

  • status: The HTTP status code represented as a string.

  • code: A machine-readable application error code.

  • title: A short, human-readable summary.

  • detail: An explanation specific to this occurrence.

  • source: A pointer or parameter identifying the invalid input. A pointer uses JSON Pointer syntax, such as /data/attributes/title.

  • meta: Additional structured details.

Use 400 Bad Request for malformed JSON or a request document that violates JSON:API’s structural requirements. A 422 Unprocessable Content response is appropriate when the document is structurally valid but fails application-level validation, although JSON:API itself does not require a particular validation status code.

Request and Response Examples

A successful request is GET /articles/1?include=author with the header Accept: application/vnd.api+json. The response status is 200 OK, the response header is Content-Type: application/vnd.api+json, and a compact body is {"data":{"id":"1","type":"articles","attributes":{"title":"Designing APIs"},"relationships":{"author":{"links":{"related":"/articles/1/author"},"data":{"type":"people","id":"42"}}}},"included":[{"id":"42","type":"people","attributes":{"name":"Aisha Khan"}}],"links":{"self":"/articles/1?include=author"}}.

A validation request is POST /articles with Content-Type: application/vnd.api+json and body {"data":{"type":"articles","attributes":{"title":""}}}. The response status is 422 Unprocessable Content, the response header is Content-Type: application/vnd.api+json, and the body is {"errors":[{"status":"422","code":"invalid-title","title":"Invalid title","detail":"title must not be empty","source":{"pointer":"/data/attributes/title"}}],"meta":{"requestId":"req_123"}}.

Trade-offs and Best Practices

  • Benefit: A common envelope reduces client-specific parsing logic and gives generic clients predictable handling for pagination, errors, relationships, and extensions.

  • Cost: Resource identifiers, relationships, included resources, links, and metadata make payloads more verbose than a purpose-built custom format.

  • Benefit: Separating attributes from relationships gives related resources explicit semantics and supports independent caching and authorization decisions.

  • Cost: Clients must understand compound documents, linkage, and include-query behavior; debugging is harder when related resources are fetched through several relationships.

  • Best practice: Use stable type, id, relationship, and error code values. Clients should branch on machine-readable codes rather than parsing human-readable text.

  • Best practice: Apply field-level authorization before placing resources in included, because related resources may expose data that the primary resource did not reveal.

  • When not to use it: A small internal API with one stable client may gain little from JSON:API’s envelope and relationship overhead. Compact, streaming, or highly specialized contracts may be better served by another format.

Sign in to keep reading

You've opened 2 full answers. Sign in to read all 50 API Design answers, mark what you know and pick up where you left off.

Report a mistake

What's wrong?

All System Design subjects