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.
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.
"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.OpenApipackage, 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
objecttypes 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."
| 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 |
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
| 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 |
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.
Checks that the candidate understands both approaches, the tooling around them, and can choose based on audience and risk rather than dogma.
Green flags
Red flags
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
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.
| 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.
A mock serves example responses straight from the spec:
prism mock openapi.yaml, validates requests against the spec too.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.
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.
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.
openapi.yaml for GET /orders and POST /orders, run npx @stoplight/prism-cli mock openapi.yaml, and call it with curl.npx @stoplight/spectral-cli lint openapi.yaml and a custom rule requiring camelCase.Microsoft.Extensions.ApiDescription.Server, and build to generate the document.oasdiff breaking reviewed.yaml generated.json and then rename a DTO property to see it fail.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
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.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.
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.
I make the committed build-time spec the contract and gate pull requests on it:
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.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.
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.
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.
Last updated 23 Nov 2026.