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.
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.
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.
What is OpenAPI (Swagger), and how does an OpenAPI specification improve API design, documentation, and developer experience? Explain how you would use the spec in continuous integration to detect breaking changes before deployment and to generate SDKs and mock servers.
Sample Answer
OpenAPI (the specification that was originally called Swagger) is a machine-readable, language-agnostic way to describe an HTTP API: every endpoint, its request and response shapes, its status codes, and its authentication requirements, written down in one YAML or JSON document. It matters because that single document becomes something both humans and tools can act on: developers read it as documentation, and tools consume it to generate mock servers, client SDKs (software development kits), and automated compatibility checks.
What the specification actually buys you
Design and documentation. Because the spec is structured (not prose), documentation generated from it (via tools like Redoc or Swagger UI) stays interactive and precise: a reader can see the exact shape of a request body and try a live call against a mock server, not just read a paragraph describing it.
Developer experience. A new engineer, or an external partner, can generate a client library in their language of choice directly from the spec instead of hand-writing HTTP calls and guessing at field names from an outdated wiki page.
Using the spec in CI (continuous integration) to catch breaking changes before deployment
The core idea: treat the OpenAPI document itself as a versioned artifact, and diff the new version against the last deployed version on every pull request.
- Store the spec in the same repository as the code, versioned alongside it, so a pull request that changes behavior also shows the corresponding spec diff in review.
- Run a schema-diff tool in CI (categories of tool: OpenAPI diff checkers, contract-testing frameworks) that classifies each change as additive (a new optional field, a new endpoint) or breaking (a removed field, a field made required, a changed type). Additive changes pass automatically; breaking changes fail the build unless explicitly approved.
- Generate SDKs and a mock server directly from the spec as a build step, so client teams consuming the generated SDK get a compile error (not a runtime surprise) when a breaking change slips through, and so a mock server is always available for frontend and QA work without waiting on the real backend.
Worked example
Suppose a pull request changes a response field total_amount from a string to a number. The CI pipeline pulls the previously-deployed spec, diffs it against the new one, and flags: "field total_amount on POST /orders response changed type from string to number, this is a breaking change for any existing consumer parsing it as a string." That failure blocks the merge until either the team reverts to an additive change (adding a new field total_amount_numeric instead of retyping the existing one) or explicitly bumps a major version and communicates the break.
Trade-offs and pitfalls
The spec is only as trustworthy as the CI gate that enforces it: an OpenAPI document that is hand-edited and never validated against the running service's actual behavior can drift silently, and the mock servers and generated SDKs built from it become confidently wrong. The breaking-change detector also needs real judgment layered in, not blind automation: a change that is technically additive (a new required header) can still break existing clients in practice, so treating the diff tool's classification as the final word rather than a first pass is a common mistake.
How should an API's error contract let a client tell a retryable failure (for example, a downstream dependency outage) apart from a non-retryable one (a validation error, an authorization failure)? Walk through the response shape, the HTTP status codes you would map to it, and what you would expose for internal observability.
Sample Answer
The response shape needs a field a client can check WITHOUT having to remember which HTTP status codes are retryable, because that mapping is exactly the kind of implicit knowledge that drifts out of sync between server and client over time. An explicit retryable: true/false field in the error body, backed by a consistent status-code mapping, is more robust than expecting every client to have memorized "5xx generally means retry, 4xx generally doesn't, except for 429."
The response shape
Every error response includes: an error code (a stable string), a retryable boolean, and where relevant a suggested retry_after hint (for a rate-limited or temporarily-unavailable case). A downstream dependency outage returns retryable: true; a validation failure or an authorization failure returns retryable: false, explicitly, rather than leaving the client to infer it from the status code alone.
Status-code mapping
Downstream outages and other transient failures map to 503 (Service Unavailable) or 504 (Gateway Timeout); validation errors map to 400; authorization failures map to 401 or 403. The important discipline is consistency: the same underlying failure category should always produce the same status code and the same retryable value, every time, so a client's retry logic can be written once against the CONTRACT rather than against the behavior of one specific endpoint it happened to test against.
Internal observability
Every error response, retryable or not, should be logged internally with its correlation ID, error code, and enough context (which downstream dependency failed, if any) to build a dashboard distinguishing "we are seeing elevated retryable failures from dependency X" from "clients are sending an elevated rate of invalid requests," which are operationally very different signals requiring different responses from the team.
Worked example
A checkout API depends on an inventory service. When the inventory service times out:
{
"error": {
"code": "inventory_service_timeout",
"retryable": true,
"retry_after_seconds": 2
}
}
mapped to HTTP 503. When a client submits an order with a negative quantity:
{
"error": {
"code": "invalid_quantity",
"retryable": false
}
}
mapped to HTTP 400. A client's retry logic checks error.retryable directly (and respects retry_after_seconds when present) rather than maintaining its own hardcoded table of "which status codes are safe to retry," which is exactly the kind of client-side assumption that drifts out of sync with server behavior as the API evolves.
Trade-offs and pitfalls
Relying purely on HTTP status code conventions without an explicit retryable field forces every client to independently encode assumptions about which codes mean what, and those assumptions silently diverge across different client implementations over time. The opposite risk, marking something retryable that actually is not (a validation error mistakenly flagged retryable) sends a client into a pointless retry loop that will never succeed and burns capacity on both sides for no benefit, so the classification itself needs to be treated as a correctness-critical part of the contract, not an afterthought bolted onto whatever status code was already being returned.
Walk me through a time you helped your team improve API or data-model consistency by introducing a review practice, template, or standard. How did you get buy-in, and what measurable outcome showed the change was worth it?
Sample Answer
The strongest version of this story treats "getting buy-in" as its own real problem to solve, not an afterthought after the standard was written: a review checklist or template that nobody asked for and that adds friction to every pull request will be quietly ignored, no matter how sound its content is, unless the people adopting it were part of shaping it or can see a concrete problem it actually prevented.
What a strong answer walks through
The recurring problem that motivated the standard. Name a specific, repeated pain point (three separate incidents where a field was renamed without warning, or a recurring pattern of inconsistent error shapes across services making client-side error handling brittle), not an abstract desire for "more consistency."
How you got buy-in, specifically. Did you pilot the template on your own team first and bring results, not just a proposal, to a wider forum? Did you involve the engineers who would actually use it in drafting it, so it reflected real workflow rather than an ideal imposed from outside? Buy-in earned through a concrete, already-demonstrated win is far more durable than buy-in secured by a mandate from above.
The measurable outcome. A credible answer names something you could actually point to: a drop in a specific class of production incident, a measured reduction in review-comment cycles for API design discussions, or an increase in some adoption metric (percentage of new endpoints using the reviewed template) tracked over a real time window, not a vague "things got better."
Worked example shape
"We had three separate incidents in one quarter where a field was silently renamed or retyped in an API response, each caught only after a client broke in production. I proposed a lightweight schema-change checklist as part of the pull request template, but rather than mandating it top-down, I piloted it on my own team's PRs for a month first, tracking how many schema-affecting changes it actually caught before merge. It caught two would-be breaking changes in that pilot month alone. I brought that concrete result, not just the proposal, to the broader engineering review, and adoption followed because people could see it had already prevented two real incidents rather than being a hypothetical improvement. Six months after wider rollout, breaking-change incidents traced to unreviewed schema changes dropped from three in the prior quarter to zero."
Trade-offs and pitfalls
A common weak point is describing the STANDARD in detail while glossing over how buy-in was actually secured, which is usually the harder and more interesting half of this story; a checklist's content is rarely the reason adoption succeeds or fails. Another common weak spot: an outcome metric that is really just "adoption happened" rather than a downstream result (fewer incidents, faster reviews) the standard was actually meant to produce; adoption is a leading indicator, not the outcome itself.
Unlock Full Question Bank
Get access to all 16 API Contracts and Schema Design interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.