📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

Contract-first or code-first: how do you design an HTTP API? Explain writing the OpenAPI document first versus generating it from code, how you run API design reviews, how generators and mock servers fit in, and which approach you would choose for a new partner-facing API on .NET 10.

Contract-first (design-first) versus code-first API development: the OpenAPI document as the source of truth, design reviews, server and client generation, mock servers, drift detection, and choosing per context.

Mid-Level Theory Intermediate api-design code-generation contract-first mock-server openapi web-api

🎯 Key points

  • Contract-first: OpenAPI YAML is designed, reviewed and versioned before code
  • Code-first: the spec is generated from ASP.NET Core endpoints (built-in OpenAPI, build-time generation)
  • Design reviews on the spec catch naming, errors and paging issues before code exists
  • Mock servers (e.g. Prism, Microcks, APIM mock responses) let consumers build in parallel
  • Generate clients with Kiota or NSwag; generating servers is optional and often skipped in .NET
  • Drift detection: diff the generated spec against the designed one in CI (oasdiff)
  • Linting with Spectral enforces guidelines on either approach
  • Choose contract-first for public, partner and multi-team APIs; code-first for internal, single-consumer APIs

⏱ 30-second answer

Contract-first means the OpenAPI document is written, reviewed and versioned before any code, and becomes the source of truth. The design review on the spec is the main payoff: naming, resource boundaries, error shapes and pagination get fixed while they cost nothing, and consumers build against a mock server in parallel and give feedback early. Code-first means you write ASP.NET Core endpoints and generate the spec from them with the built-in OpenAPI support, ideally at build time.

Code-first is faster for internal APIs with one consumer. Contract-first pays off when the API is public, partner-facing or crosses teams.

In .NET I usually do a hybrid: design and review the spec first, implement code-first, then diff the generated spec against the reviewed one in CI so they can't drift. The trade-off is upfront design time against the cost of breaking changes later.

🗣 Full answer (senior)

How I would answer this in an interview

"The question is where the source of truth lives. In contract-first, or design-first, the OpenAPI document is the product. You write it, review it with consumers, lint it against your guidelines, publish a mock, and only then implement. In code-first, the C# is the truth and the OpenAPI document is a by-product generated from endpoint metadata, which in .NET 10 is the built-in Microsoft.AspNetCore.OpenApi package, optionally generated at build time so it's committed and diffable.

For a partner API I'd go design-first, because the expensive mistakes in an API are naming, resource boundaries, error shapes and pagination, and they're easiest to fix before anyone has integrated. For example, at [company] we [reviewed a payments API spec with two partners before writing code]. The review caught [a money field modelled as a float and a missing idempotency key], and the partners started building against a Prism mock the same week, so integration testing started [three weeks] earlier than usual. I don't usually generate the server from the spec in .NET; generated controllers are awkward to own. Instead I implement the endpoints by hand and add a CI step that generates the OpenAPI document from the code and diffs it against the reviewed spec with oasdiff. Any difference fails the build, so the implementation can't silently drift from what we promised.

The mistake I see is teams claiming contract-first while the YAML rots in a wiki after week two, or claiming code-first while nobody ever looks at the generated document, so it's full of object types and missing error responses. Whichever you pick, the spec has to be linted, reviewed and checked in CI. For an internal API with one consuming team in the same repo, code-first with build-time generation is perfectly fine and faster."


The two approaches

Contract-first (design-first) Code-first
Source of truth OpenAPI YAML in git C# endpoints and DTOs
First artefact Spec + mock server Running code
Review happens on The spec (PR on YAML) The code, sometimes the generated spec
Consumers can start Immediately, against a mock When an environment is deployed
Risk Spec and code drift Accidental contract changes from refactors
Tooling in .NET Spectral, Prism/Microcks, Kiota/NSwag clients, oasdiff Built-in OpenAPI, Microsoft.Extensions.ApiDescription.Server, oasdiff

The hybrid I use

1. Draft openapi.yaml  ─► 2. Spectral lint + design review PR (consumers invited)
                                 │
                                 ▼
3. Publish mock (Prism / APIM mock policy) ─► consumers build against it
                                 │
                                 ▼
4. Implement Minimal API endpoints by hand
                                 │
                                 ▼
5. CI: build-time OpenAPI generation ─► oasdiff (reviewed spec vs generated) ─► fail on difference

What a design review checks

Area Questions
Resources and naming Nouns, plural collections, consistent casing, no internal names
Data types Money as decimal string or minor units, dates with offsets, enums extensible
Errors ProblemDetails, documented codes per operation
Collections Cursor pagination, max page size, filters allow-listed
Reliability Idempotency keys on POST, ETags for updates, rate limit headers
Security Auth scheme, scopes per operation, no personal data in URLs

Production example

On a partner onboarding API, design-first with a mock let [three] partners build in parallel with our implementation. The spec diff gate in CI caught [seven] accidental contract changes in the first six months, such as a renamed property after a refactor, each of which would otherwise have reached production.

🔍 What the interviewer is checking

Checks that the candidate understands both approaches, the tooling around them, and can choose based on audience and risk rather than dogma.

Green flags

  • Explains design reviews and mocks as the real benefit of contract-first
  • Knows .NET's built-in OpenAPI and build-time generation
  • Proposes drift detection in CI
  • Chooses differently for partner versus internal APIs

Red flags

  • Thinks generating a spec equals documenting an API
  • No answer for spec/code drift
  • Dogmatic about one approach for everything

📚 Learn in depth

1. Why the contract matters more than the code

Once a client integrates, the contract is frozen in their code. Changing C# is cheap; changing a published contract means versioning, deprecation and months of migration. Design-first moves design effort to the point where change is cheapest.

cost of change
   ▲
   │                                      ┌── after partners integrate
   │                        ┌── in production
   │            ┌── in code
   │   ┌── in spec review
   └───┴────────────┴───────────────┴─────────────┴─────► time

2. How code-first generation works in .NET 10

Microsoft.AspNetCore.OpenApi reads endpoint metadata from API Explorer: route templates, parameter binding, Produces/ProducesProblem, TypedResults return types, and JSON schema derived from your DTOs via System.Text.Json contracts. .NET 10 defaults to OpenAPI 3.1 and supports YAML output. Adding Microsoft.Extensions.ApiDescription.Server generates the document during dotnet build, so you can commit it and diff it in pull requests.

Code-first's weakness is that the spec reflects whatever the code says, including accidents: a renamed property, a nullable change, a missing error response.

3. Generating code from a contract

Generate Tool Verdict in .NET
Clients (C#, TypeScript) Kiota, NSwag Common and valuable
Server stubs / controllers NSwag, OpenAPI Generator Possible; generated code is hard to own and regenerate over hand edits
DTOs only NSwag, custom templates Middle ground; endpoints written by hand

Most .NET teams generate clients, not servers, and use the diff gate to keep the hand-written server honest.

4. Mock servers

A mock serves example responses straight from the spec:

  • Prism (Stoplight, open source): prism mock openapi.yaml, validates requests against the spec too.
  • Microcks: mocks plus contract testing, runs in Kubernetes.
  • Azure API Management: the mock-response policy returns examples from the operation definition before a backend exists.

Good examples in the spec make mocks useful, so examples are part of the review.

5. Drift detection

reviewed openapi.yaml (git)  ─┐
                               ├─► oasdiff diff --fail-on ERR
generated openapi.json (build) ┘      │
                                      ▼
                      breaking or unexpected differences fail the PR

For intentional changes, the PR updates the reviewed spec too, which triggers the design review again. That's the mechanism that keeps design-first honest.

6. Linting

Spectral rulesets encode your guidelines (camelCase properties, problem+json for 4xx, pagination parameters on collections, operationId present). Run it on the designed spec, the generated spec, or both.

Try it yourself

  1. Write a small openapi.yaml for GET /orders and POST /orders, run npx @stoplight/prism-cli mock openapi.yaml, and call it with curl.
  2. Lint it with npx @stoplight/spectral-cli lint openapi.yaml and a custom rule requiring camelCase.
  3. Implement the endpoints in a Minimal API, add Microsoft.Extensions.ApiDescription.Server, and build to generate the document.
  4. Run oasdiff breaking reviewed.yaml generated.json and then rename a DTO property to see it fail.
  5. Generate a C# client with Kiota from the reviewed spec and call the running API with it.

💻 Code

The hybrid: a reviewed spec in git, a hand-written endpoint, build-time generation and a CI diff gate.

# api/orders.openapi.yaml (reviewed contract, excerpt)
openapi: 3.1.0
info: { title: Orders API, version: '1.0' }
paths:
  /v1/orders/{id}:
    get:
      operationId: getOrder
      parameters:
        - { name: id, in: path, required: true, schema: { type: integer } }
      responses:
        '200':
          description: The order
          content:
            application/json:
              schema: { $ref: '#/components/schemas/Order' }
              example: { id: 42, reference: 'ORD-0042', total: { amount: '120.50', currency: AUD } }
        '404':
          description: Not found
          content:
            application/problem+json:
              schema: { $ref: '#/components/schemas/ProblemDetails' }
// Program.cs - implemented by hand to match the contract.
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddOpenApi(); // code-first generation, used only to verify against the contract

var app = builder.Build();
app.MapOpenApi();

app.MapGet("/v1/orders/{id:int}", Results<Ok<OrderDto>, ProblemHttpResult> (int id) =>
        id == 42
            ? TypedResults.Ok(new OrderDto(42, "ORD-0042", new MoneyDto("120.50", "AUD")))
            : TypedResults.Problem(statusCode: 404, title: "Order not found"))
    .WithName("getOrder");   // operationId must match the contract

app.Run();

public sealed record MoneyDto(string Amount, string Currency); // decimal as string: no float rounding in clients
public sealed record OrderDto(int Id, string Reference, MoneyDto Total);
<!-- Orders.Api.csproj: generate the OpenAPI document during build -->
<ItemGroup>
  <PackageReference Include="Microsoft.Extensions.ApiDescription.Server" Version="10.0.*" PrivateAssets="all" />
</ItemGroup>
<PropertyGroup>
  <OpenApiDocumentsDirectory>$(MSBuildProjectDirectory)/../artifacts/openapi</OpenApiDocumentsDirectory>
</PropertyGroup>
# CI: lint the contract, then fail if the implementation drifted from it.
npx @stoplight/spectral-cli lint api/orders.openapi.yaml --fail-severity=error
dotnet build src/Orders.Api -c Release
oasdiff diff api/orders.openapi.yaml artifacts/openapi/Orders.Api.json --fail-on ERR

⚠ Common mistakes

  • Mistake: Writing the spec first, then never updating it. Why it is wrong: The documented contract and the real API diverge, and consumers trust the wrong one. Instead: Diff the generated spec against the reviewed one in CI.
  • Mistake: Code-first without ever reviewing the generated document. Why it is wrong: Refactors silently change the contract and the spec fills with object and missing errors. Instead: Commit the build-time spec, review its diff in every PR, and declare every outcome with TypedResults and Results<...> return types so the generator documents each status code.
  • Mistake: Generating server controllers and then hand-editing them. Why it is wrong: The next regeneration overwrites the edits, so teams stop regenerating. Instead: Generate clients and DTOs; write endpoints by hand behind a diff gate.
  • Mistake: Design reviews without consumers. Why it is wrong: The team optimises for its own model, not the client's tasks. Instead: Invite at least one consuming team or partner to the spec review.
  • Mistake: Engaging consumers only at the first review. Why it is wrong: Their needs change and the API evolves, so later changes surprise them. Instead: Keep a standing channel (changelog, partner check-ins, preview environments with the mock) and invite them to review every contract change.
  • Mistake: Specs without examples. Why it is wrong: Mocks return useless placeholder data and docs are hard to read. Instead: Treat examples as required and lint for them.
  • Mistake: Choosing contract-first for a throwaway internal endpoint. Why it is wrong: Ceremony with no consumer to benefit. Instead: Code-first with build-time generation is fine for single-consumer internal APIs.

🏛 Senior insight: trade-offs

The debate isn't really YAML versus C#; it's whether the contract gets a deliberate design review before clients depend on it, and whether anything stops it drifting afterwards. In .NET, the hybrid (design and review the spec, implement by hand, gate on a diff) gets most of the benefit without fighting generated server code.

Option When it fits Cost When not to
Pure contract-first with server generation Polyglot organisations, strict governance Owning generated code Teams that need idiomatic, hand-tuned .NET endpoints
Hybrid: reviewed spec + hand-written code + diff gate Partner and multi-team APIs in .NET Keeping two artefacts in sync (automated) Single-consumer internal APIs
Code-first with build-time spec Internal APIs, BFFs, one consuming team Contract changes only visible in spec diffs Public APIs with many external consumers

I measure it by how many contract changes reach consumers unannounced (target zero) and how early consumers start integration testing.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions build-time OpenAPI generation or client generation Why: Checks hands-on knowledge of ApiDescription.Server, committing the spec, and Kiota/NSwag.
    How to answer

    Adding the Microsoft.Extensions.ApiDescription.Server package makes dotnet build produce the OpenAPI document. It launches your app's entry point with an inert server, asks the registered document provider for each document, and writes {Project}.json to obj (or to OpenApiDocumentsDirectory). Because your start-up code runs during build, guard anything that connects to databases or Key Vault.

    I commit the spec: API changes then show up as diffs in pull requests, CI can fail when the regenerated file differs, and clients are generated from a file rather than a running server. For clients I use Kiota (C#, TypeScript, Go, Python...) or NSwag (C#, TypeScript).

    The trade-off: a slightly slower build and a guarded Program.cs, in exchange for a contract you can review, diff and generate from.

  2. When: Candidate mentions diffing specs or linting in CI Why: Checks the CI contract gate: oasdiff, Spectral and per-version documents.
    How to answer

    I make the committed build-time spec the contract and gate pull requests on it:

    1. Drift check: rebuild and fail if the generated spec differs from the committed one.
    2. Breaking-change check: oasdiff breaking compares the PR's spec with main and the last released spec, and fails on removed paths or properties, new required request fields, narrowed enums or changed types.
    3. Lint: Spectral rules for house style (operationIds, ProblemDetails errors, naming).
    4. Versioning: one document per major version (AddOpenApi("v1"), AddOpenApi("v2")), so breaking changes go into a new version while v1 stays frozen.

    The trade-off: CI becomes stricter and occasionally needs a deliberate override, but breaking changes become explicit decisions instead of production incidents.

  3. When: Candidate talks about designing partner-facing APIs Why: Checks broader public API design: resource model, guidelines and evolution.
    How to answer

    I start from partner use cases and the domain, modelling resources around stable business concepts rather than tables. I adopt a published baseline (the Azure or Microsoft Graph REST API guidelines, which replaced Microsoft's original general guidelines; Google AIP or Zalando are good alternatives) and write a short house style: naming, JSON conventions, dates with offsets, money as decimal plus currency, opaque ids, one error shape (RFC 9457 ProblemDetails with error codes) and one paging shape (cursor plus nextLink).

    Then I design for evolution: additive changes only, tolerant readers, a written deprecation policy with Sunset headers, and rare major versions. Security is OAuth 2.0 client credentials with scopes, rate limits and idempotency keys. Partners experience the API through OpenAPI, examples, a sandbox, SDKs and a changelog. The trade-off is upfront design and governance effort versus years of breaking partner integrations.

🛠 Real-world problems: how you handle them

Spec drift broke a partner's generated client
Situation
A partner API for [insurance quotes] was designed contract-first, but after launch developers changed code without touching the YAML. [Two] partners generated C# and TypeScript clients from the published spec.
Signals
A partner reported deserialisation failures after a Tuesday release; their logs showed `premium` arriving as an object while the spec said a number. Application Insights showed a jump in 400s from that partner because their retries resent stale payloads.
Investigation
Generated the OpenAPI document from the deployed build and ran oasdiff against the published spec: [nine] differences, including the `premium` type change, two renamed properties and an undocumented 409. Git history showed none of the PRs had touched the spec file.
Resolution
Immediate: restored the old `premium` shape behind a v1 mapping and shipped the object form only in a new v2 document. Real fix: added build-time OpenAPI generation and an oasdiff gate comparing the generated document to the published spec on every PR, plus Spectral linting.
Prevention
Contract changes now require a spec PR reviewed by the API guild; the CI gate fails on any unreviewed difference; partners subscribe to a changelog generated from the spec diffs.

How to tell it (STAR)

**S:** Our quotes API had been designed contract-first, but the code drifted from the published spec, and a release changed `premium` from a number to an object, breaking a partner's generated client. **T:** I needed to restore the partner quickly and stop drift happening again. **A:** I generated the spec from the running build, diffed it with oasdiff and found [nine] undocumented differences. I restored the old shape for v1, moved the change to v2, and added a CI gate that fails any PR where the generated spec differs from the reviewed one. **R:** The partner was back within [a day], and in the next [six] months the gate blocked [seven] accidental contract changes before they shipped.

More in API Design

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me