API Contracts and Schema Design Questions
Defining the interface contract between producers and consumers: request/response payload shapes, data models, field-level validation, nullability, and enum/typing decisions (including safely evolving an enum's allowed values without breaking clients). Covers contract-first design with OpenAPI and JSON Schema (authoring specs, generating SDKs and mock servers, catching breaking changes in CI), mapping internal domain models to external DTOs as both evolve independently, and designing a stable error-response contract (structured error codes, correlation IDs, retryable classification). Also covers the leadership and behavioral practice of establishing and governing contract standards across teams. The contract is the durable artifact clients depend on.
Write a minimal OpenAPI 3.1 specification (YAML) for a POST /orders endpoint on an e-commerce service. Include the request body schema (items: an array of objects with product_id and quantity), a 201 success response schema (order_id, total_amount), 400 and 401 error responses, and an example request and response embedded in the spec.
Sample Answer
The spec needs a request body schema for the array of order items, a 201 response schema for the created order, and explicit 400 and 401 error responses, each with an embedded example so a reader can see the exact shape without inferring it from the schema alone.
The specification
openapi: 3.1.0
info:
title: Orders API
version: "1.0.0"
paths:
/orders:
post:
operationId: createOrder
requestBody:
required: true
content:
application/json:
schema:
type: object
required: [items]
properties:
items:
type: array
minItems: 1
items:
type: object
required: [product_id, quantity]
properties:
product_id:
type: string
quantity:
type: integer
minimum: 1
example:
items:
- product_id: "sku_1001"
quantity: 2
- product_id: "sku_2044"
quantity: 1
responses:
"201":
description: Order created
content:
application/json:
schema:
type: object
required: [order_id, total_amount]
properties:
order_id:
type: string
total_amount:
type: number
example:
order_id: "ord_7f3a"
total_amount: 64.50
"400":
description: Validation error
content:
application/json:
schema:
type: object
required: [error_code, message]
properties:
error_code:
type: string
message:
type: string
example:
error_code: "invalid_quantity"
message: "quantity must be at least 1"
"401":
description: Missing or invalid credentials
content:
application/json:
schema:
type: object
properties:
error_code:
type: string
example:
error_code: "unauthorized"
This document was parsed and structurally checked with a YAML parser: it parses cleanly as valid YAML, declares openapi: 3.1.0, defines the /orders path with the post operation described above, and every example object matches the shape its sibling schema declares (the 201 example has both order_id and total_amount, matching the required list; the 400 example has both error_code and message).
Design decisions worth calling out
itemsrequiresminItems: 1, so an order with zero line items is rejected at the schema level rather than reaching business logic.quantityhasminimum: 1, catching a zero-or-negative quantity the same way, at the contract layer.- The 400 response has a structured shape (
error_codeplusmessage), not a bare string, so a client can branch onerror_codeprogrammatically instead of pattern-matching on human-readable text.
Trade-offs and pitfalls
Keeping this spec minimal (one endpoint, three responses) makes it easy to read in an interview or a code review, but a production version would need to decide, and document, what OTHER error shapes exist (a 404 if referencing a nonexistent product_id, a 409 for a stock conflict) so the response schema doesn't quietly grow undocumented shapes over time as edge cases get patched in. A second real trade-off: embedding literal examples directly in the spec (as done here) is excellent for readability and for generating realistic mocks, but every example needs to be kept in sync with the schema by hand or by a linter; an example that drifts from its own schema is worse than no example, because it actively misleads a reader.
Explain contract-first (OpenAPI-first) versus code-first API development. Discuss how each approach impacts documentation quality, SDK generation, design reviews, iteration speed, and coordination with product and client teams in a cross-functional environment.
Sample Answer
Contract-first (also called design-first) means writing the OpenAPI specification before any implementation code exists, and treating that spec as the source of truth the rest of the process is built around. Code-first means implementing the endpoints first and generating the spec afterward, usually from code annotations. The trade-off is speed now versus alignment later: code-first ships an initial version faster, contract-first spends that time up front and gets it back many times over as the API grows.
How each choice plays out in practice
Documentation quality. Contract-first documentation is authored intentionally and reviewed as a deliverable in its own right, so it tends to describe intent, not just implementation detail. Code-first documentation is generated from whatever the code happens to do, so it is only as good as the annotations a developer remembered to write, and it can drift the moment someone edits a handler without updating the annotation.
SDK generation. Contract-first lets you generate client SDKs (software development kits), in multiple languages, before a single endpoint is implemented, because the spec is a complete, self-contained artifact. Code-first SDK generation has to wait for the code to exist, and if the spec is only produced from annotations, gaps in those annotations become gaps in the generated client (an endpoint the annotations mislabeled generates a client method with the wrong shape).
Design reviews. A written spec is something a reviewer, a frontend engineer, or an external partner can read and comment on before any implementation exists, which surfaces disagreements about the shape of the contract while they are still cheap to fix. Reviewing a code-first API usually means reviewing a pull request that already contains the implementation, so a disagreement about the contract's shape now means reworking real code, not just a document.
Iteration speed. For a small, fast-moving internal service with few consumers, code-first is genuinely faster: you skip the spec-authoring step and let the framework generate documentation as a side effect. That advantage shrinks, and can invert, once there are multiple independent consumer teams who need the contract stabilized before they start their own work.
Coordination across teams. This is where contract-first tends to win as the organization grows. A stable, reviewed spec becomes the coordination artifact multiple teams can build against in parallel: product managers get a concrete, reviewable artifact to confirm the contract actually matches the intended business requirements before a single line of implementation exists, instead of discovering a scope mismatch during a late-stage demo; frontend engineers write against mocked responses generated straight from the spec, and partner integrations get a concrete document to implement against, all before the backend team ships a single endpoint.
Worked example: the same endpoint, two orders of operations
Contract-first: write the OpenAPI document for POST /orders (request schema, response schema, error responses) -> review it with the frontend and partner teams -> generate a mock server from it so the frontend team starts building immediately -> implement the backend against the now-frozen spec -> validate the real implementation against the spec in CI.
Code-first: implement POST /orders -> annotate the handler with the framework's OpenAPI decorators -> generate the spec from those annotations -> frontend team waits for either the real endpoint or a manually-maintained mock, because no independent spec existed to generate one from earlier.
Trade-offs and pitfalls
Contract-first fails when the spec is written once and never re-validated against the implementation: without a CI (continuous integration) check that diffs the running service's actual behavior against the spec, the two drift apart just as easily as in code-first, except now with a false sense of security because "we have a spec." Code-first fails quietly: a subtle annotation mistake (a field the code treats as optional but the annotation marks required) produces a generated SDK that is wrong in a way nobody notices until a client hits it in production. Neither approach is safe without a CI gate that continuously checks the deployed behavior against the published contract, whichever one is authoritative.
You need to add new enum values to a public API response without breaking older clients that may error or crash on an unrecognized value. Propose both server-side and client-side strategies to make this safe, and describe how you would migrate the schema and communicate the change to minimize client impact.
Sample Answer
The safest approach combines both sides: design the client to treat unrecognized enum values as a known, handled case (never a crash), and design the server rollout so the new value only starts appearing after clients have had a chance to deploy that handling.
Server-side strategies
Prefer strings over closed enums where the value set is expected to grow. If the API's own schema does not hard-enforce a closed enum (or uses an "open" pattern that documents known values without technically restricting the wire format to them), adding a new value is a purely additive change with nothing to coordinate on the server side.
Stage the rollout. Add the new value to the documentation and to a small percentage of test traffic before it appears broadly, giving client teams a window to deploy defensive handling against a real, already-defined value rather than a hypothetical future one.
Version the schema explicitly if the enum is truly closed (a formal JSON Schema enum constraint with no forward-compatibility clause): adding a value is then treated as a breaking change requiring a new API version, which is the conservative, slower, but bulletproof path.
Client-side strategies
Always include a default/unknown branch. Any code that switches on the enum's value needs an explicit "unrecognized value" branch, treated as a real code path to test, not an afterthought: log it, degrade gracefully (show a generic label instead of crashing), and move on.
Treat the enum as open by default, even if it currently only has three values, unless the contract explicitly documents it as closed. Writing an exhaustive switch statement with no default case is the single most common way this breaks in practice.
Worked example: migrating an order-status enum
An order-status field currently has values pending, shipped, delivered. The team wants to add returned.
- Client audit first: confirm (via API usage logs, or a client-side telemetry event on the "unknown status" branch) that consuming clients actually have a default/unknown handler; if telemetry shows zero hits on an unknown-value path today, that is itself informative (either nobody has an unknown handler, worth flagging before rollout, or the handler exists and has simply never fired yet).
- Document and communicate
returnedas a new value, giving client teams a fixed window (for example, 30 days) to confirm their unknown-value handling covers it, even though nothing about the wire contract has changed yet. - Start emitting
returnedin production, initially on a small fraction of traffic (a single test account, then a small tenant cohort) to catch a client with no real default handling before it hits every consumer at once. - Roll out to all traffic, monitoring the same "unknown status" telemetry sinks to see the metric spike briefly then fall to zero as clients pick up the new value in their own next deploys.
Trade-offs and pitfalls
The most common mistake is treating "unknown enum value" handling as a theoretical concern until the first time it actually happens in production, at which point some client somewhere is crashing on the very first real-world new value, with no staged rollout to catch it earlier. The conservative alternative, always requiring a new major version for any new enum value, is bulletproof but slow, and if applied to every genuinely additive value, teams tend to route around it by not modeling values as enums at all and losing the schema's documentation value entirely.
Explain normalization versus denormalization in your API's response shape, from the consumer's perspective. When would you prefer a normalized response, and when would you intentionally duplicate data into a read model or a single response payload instead?
Sample Answer
From the consumer's side, normalization means the response gives you references (an ID) that you must resolve with a further call, while denormalization means the response embeds the related data directly so no follow-up call is needed. The right choice depends on how the client is actually going to use the data, not on how the backend's database happens to be structured.
When a normalized response is the better choice
Prefer references when the related data is large, changes independently of the primary resource, or is rarely needed by the majority of callers. Returning an order with just a customer_id (instead of the customer's full profile embedded) keeps the response small for the common case where a caller only needs the order itself, and avoids serving stale customer data that has since changed, since the client fetches the customer separately only when it actually needs it.
When denormalizing into the response is the right call
Prefer embedding data directly, effectively building a small denormalized read model into the response, when the consuming client needs it on nearly every call and a follow-up round trip would be a real cost: a mobile app rendering an order list screen that always shows the customer's name benefits from the API embedding customer_name directly, trading a slightly larger and slightly less "pure" response for avoiding an extra network round trip on every single request.
Worked example
An orders API serving two very different consumers:
- An internal reconciliation job that only needs order totals and IDs: a normalized response (just
customer_id, not the customer object) keeps the payload small across millions of rows and avoids duplicating customer data that changes independently. - A mobile order-history screen that always displays the customer's name and the first product's thumbnail: a denormalized response embedding
customer_nameandfirst_item_thumbnail_urldirectly saves that client two round trips it would otherwise make on every single screen load.
The same underlying order table can back both: the choice is made at the API-response layer, not at the storage layer, precisely because the two consumers have different access patterns.
Trade-offs and pitfalls
Denormalizing into a response means that data can go stale between the time it was embedded and the time the client reads it, so anything embedded needs a story for how staleness is acceptable (or how the client gets told an embedded value might be out of date). Normalizing everything, on the other hand, pushes N+1-style round trips onto every consumer regardless of their actual access pattern, penalizing the common case for the sake of theoretical purity. A frequent middle-ground pattern is offering both: a lean, normalized response by default, with an explicit expansion parameter (?expand=customer) that lets a caller opt into the denormalized fields only when it actually needs them.
Your team wants to add a computed field to an existing API response, but the value is expensive to calculate and could materially change the response time. How would you decide whether to compute it synchronously, cache it, materialize it in storage ahead of time, or expose it through a separate endpoint instead?
Sample Answer
The decision hinges on two independent questions: how often is this field actually read relative to how often the underlying data changes, and how expensive is the computation relative to the latency budget of the endpoint it would live on. Getting the pairing right (cheap-and-frequent versus expensive-and-rare) is what separates a good answer from a checklist of four generic options.
The four options, and when each wins
Compute synchronously, inline in the response. Only viable if the computation is genuinely cheap relative to the endpoint's existing latency budget; adding a moderately expensive computation directly into a hot-path response risks making every caller pay a cost that only some of them actually need.
Cache the computed value. A strong fit when the underlying data changes far less often than the field is read (a product's aggregate rating computed from reviews that arrive far less frequently than the product page is viewed): compute once, serve many times, with a clear invalidation trigger (recompute when a new review lands, or on a time-based TTL (time-to-live) if slight staleness is acceptable).
Materialize it in storage ahead of time. The right choice when the computation is too expensive to redo per-cache-miss and the read pattern is frequent and predictable enough to justify pre-computing and storing the result as data, updated by a background job or an event trigger rather than computed on any request path at all.
Expose it through a separate endpoint. The right choice when only a MINORITY of callers actually need the field, since folding an expensive computation into the primary response penalizes every caller (including the majority who never wanted it) to serve the few who do; a separate, explicitly-named endpoint lets the cost be paid only by the consumers who ask for it.
Worked example
A product page's response currently includes basic fields (name, price, description) served in under 50ms. The team wants to add a computed similar_products field requiring a moderately expensive similarity computation across the catalog, roughly 200ms.
- If most callers of this endpoint (analytics jobs, internal tooling) never use
similar_products, but the customer-facing web page always renders it: expose it through a separate endpoint (GET /products/{id}/similar) so the majority of callers keep their fast response, and the web page issues a second, parallel request specifically for the expensive field. - If the underlying catalog data changes only a few times a day but the product page is viewed millions of times: cache the computed value, recomputing on a catalog-change event rather than per-request, so the 200ms cost is paid rarely instead of on every page view.
Trade-offs and pitfalls
Folding an expensive field directly into the primary response "for convenience" is the most common mistake: it looks simpler in the short term (one endpoint, one call) but silently taxes every caller of that endpoint with the new field's cost, including callers who will never read it. The opposite mistake, splitting out a separate endpoint for a field nearly every caller actually needs, just adds an extra round trip for the common case; the decision genuinely depends on measuring who calls this endpoint and how they use the response, not on a general preference for either simplicity or slimness.
Unlock Full Question Bank
Get access to all 15 API Contracts and Schema Design interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.