Architecture question on contract-as-code for ASP.NET Core APIs: a committed build-time spec, breaking-change detection with oasdiff against main and released versions, Spectral linting, one OpenAPI document per major version with Asp.Versioning or group names, and how this fits with consumer-driven contract tests.
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 treat the OpenAPI document as the contract and put it in the pipeline like any other artefact. The service generates the spec at build time and the file is committed, so the first CI check is simple: rebuild and fail if the committed file is stale. That guarantees the spec in the pull request is the real one.
The second check compares that spec with two baselines: the one on
main, and the one from the last released version. I use oasdiff for this.oasdiff breakingclassifies every change, and with--fail-on ERRthe job fails on things that break existing clients: a removed endpoint or response property, a request field that became required, an enum value removed, a type change, a response field that can now be null. Additive changes, like a new optional field or a new endpoint, pass. I also publish the full changelog as a pull request comment so reviewers see the API impact without reading JSON. Then Spectral lints the spec against our style rules: every operation has an operationId, errors use ProblemDetails, paths are kebab-case.For example, at [company] we had [six] consumer teams and breaking changes kept reaching them by surprise. I [introduced] the drift check, oasdiff against the released spec and per-version documents: v1 frozen, breaking work only in v2. A breaking change could only merge with a
breaking-change-approvedlabel and a named reviewer. In [the first quarter] it blocked [five] accidental breaks, and the planned ones went out as v2 with a deprecation header on v1. The mistake I see is versioning the URL but not the contract: if v1's document can still change freely, the version number means nothing."
PR opened
-> dotnet build (regenerates openapi/v1.json, openapi/v2.json)
-> git diff --exit-code openapi/ (drift)
-> spectral lint openapi/*.json (style)
-> oasdiff breaking main/v1.json pr/v1.json --fail-on ERR
-> oasdiff breaking release/v1.json pr/v1.json --fail-on ERR
-> oasdiff changelog -> PR comment
-> generate clients from the spec (compile consumers' SDKs)
| Change | Breaking for existing clients? |
|---|---|
| Add an endpoint or optional request field | No |
| Add a response property | Usually no (unless clients use strict deserialisation) |
| Remove or rename a response property | Yes |
| Make a request field required | Yes |
| Remove an enum value from a response | Yes; adding one can break strict clients too |
Change a type (integer to string) |
Yes |
| Make a response property nullable | Yes for strongly typed clients |
| Approach | How | Fit |
|---|---|---|
| Group names | MapGroup("/v1").WithGroupName("v1"), AddOpenApi("v1") (default ShouldInclude matches group names) |
Simple, few versions |
| Asp.Versioning | AddApiVersioning().AddApiExplorer(o => o.GroupNameFormat = "'v'VVV"), one document per version |
Header, query or URL versioning, sunset policies |
With per-version documents and oasdiff against the released v1 spec, we went from [4] consumer-reported breaking changes in a quarter to [zero]. The PR comment changelog cut review time for API changes because reviewers read "removed property customerName from GET /orders/{id} 200" instead of a JSON diff.
Checks that the candidate can design a contract governance process, not just generate a document.
Green flags
Red flags
Code --(build)--> openapi/v1.json --(commit)--> Git history
|
+-------------+-------------+-------------+
v v v v
drift check oasdiff Spectral client generation
(breaking) (style) (compile consumers)
The spec is generated, so it can't be forgotten; it's committed, so it has history and diffs; and it's machine-readable, so tools can reason about compatibility.
oasdiff loads both documents, resolves $refs and compares paths, operations, parameters, request bodies and response schemas. Each difference gets a rule id (for example response-property-removed, request-property-became-required) and a level: ERR (breaking), WARN (possibly breaking), INFO. Direction matters: a new required field breaks requests, a removed property breaks responses. That asymmetry is why "adding a field" can be safe or breaking depending on which side it's on.
Compare against two baselines:
main: catches breaks introduced by this PR.Spectral uses a ruleset (.spectral.yaml) that extends spectral:oas with your rules: operationId required, 4xx/5xx responses use application/problem+json, no 200 without a schema, tags on every operation. Lint catches design inconsistency; oasdiff catches compatibility.
AddOpenApi("v1") and AddOpenApi("v2"). By default an endpoint is included when its group name matches the document name, or when it has no group name. Set ShouldInclude for custom rules.Asp.Versioning.Http and its API Explorer package), each API version becomes a group name, so the same pattern produces one document per version, and Sunset/deprecation policies can add headers.A spec diff can't see behaviour: a field that still exists but now means something else, a default that changed, an ordering clients rely on. For external or high-value consumers, add consumer-driven contract tests (Pact): consumers publish expectations, the provider verifies them in CI. Spec checks are cheap and universal; contract tests are precise but need consumer buy-in.
oasdiff breaking old.json new.json.AddOpenApi("v1") and AddOpenApi("v2") with route groups using WithGroupName and compare the two files.Per-version documents in ASP.NET Core, then the CI checks.
// Program.cs: one OpenAPI document per major version
using Microsoft.AspNetCore.Http.HttpResults;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddOpenApi("v1"); // includes endpoints whose group name is "v1"
builder.Services.AddOpenApi("v2");
var app = builder.Build();
app.MapOpenApi(); // /openapi/v1.json and /openapi/v2.json
var v1 = app.MapGroup("/v1/orders").WithGroupName("v1").WithTags("Orders");
v1.MapGet("/{id:int}", (int id) => TypedResults.Ok(new OrderV1(id, "Jane Citizen")))
.WithName("GetOrderV1"); // frozen: only additive changes allowed
var v2 = app.MapGroup("/v2/orders").WithGroupName("v2").WithTags("Orders");
v2.MapGet("/{id:int}", (int id) => TypedResults.Ok(new OrderV2(id, new Customer("Jane", "Citizen"))))
.WithName("GetOrderV2"); // the breaking reshape lives here
app.Run();
public sealed record OrderV1(int Id, string CustomerName);
public sealed record OrderV2(int Id, Customer Customer);
public sealed record Customer(string GivenName, string FamilyName);
# .github/workflows/api-contract.yml
name: api-contract
on: pull_request
jobs:
contract:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with: { fetch-depth: 0 }
- uses: actions/setup-dotnet@v4
with: { dotnet-version: '10.0.x' }
- run: dotnet build src/Orders.Api -c Release
- name: Spec is up to date
run: git diff --exit-code src/Orders.Api/openapi/
- name: Lint
run: npx @stoplight/spectral-cli lint src/Orders.Api/openapi/*.json --ruleset .spectral.yaml
- name: Breaking changes vs main and last release
run: |
git show origin/main:src/Orders.Api/openapi/v1.json > main-v1.json
git show $(git describe --tags --abbrev=0 origin/main):src/Orders.Api/openapi/v1.json > release-v1.json
oasdiff breaking main-v1.json src/Orders.Api/openapi/v1.json --fail-on ERR
oasdiff breaking release-v1.json src/Orders.Api/openapi/v1.json --fail-on ERR
# .spectral.yaml: house rules on top of the standard OpenAPI ruleset
extends: ["spectral:oas"]
rules:
operation-operationId: error
errors-use-problem-details:
description: 4xx and 5xx responses use application/problem+json
given: "$.paths.*.*.responses[?(@property >= '400')].content"
then: { field: "application/problem+json", function: truthy }
severity: error
main. Why it is wrong: Several individually "safe" PRs can add up to a break against what is actually released. Instead: Also compare with the last released spec.Deprecation and Sunset headers, and track which consumers still call old versions.Contract checks move the breaking-change decision from "a consumer finds out in production" to "a reviewer approves it in a pull request". The senior design choices are which baselines to compare against, what the override process is, and how many versions you are willing to run. I set a written policy (additive changes in place, breaking changes only in a new major version with at least [6 months] of deprecation, Deprecation and Sunset headers, and a notice to every known consumer) and let CI enforce the mechanical part, so reviews focus on intent. Usage telemetry per version (Application Insights or API Management analytics by client id) tells you when it's actually safe to retire v1.
With many teams, governance has to scale without a central bottleneck. I publish the pipeline as a reusable template (a GitHub Actions reusable workflow or Azure Pipelines template) and the Spectral ruleset as a shared package, so every service gets the same drift, lint and oasdiff checks by default. Teams own their overrides; a small API guild owns the ruleset and the compatibility policy and reviews only the exceptions. Consistency across versions comes from the same ruleset running on every document, old and new.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Drift check only | Single internal consumer | Minimal | External consumers |
| oasdiff vs main + release | Most APIs with several consumers | One CI job, occasional overrides | Prototypes |
| Shared Spectral ruleset + pipeline template | Several teams publishing APIs | Ruleset upkeep by a guild | One small service |
| Per-major-version documents | Public or partner APIs | Running and testing old versions | Internal APIs where you can update all consumers together |
| Consumer-driven contract tests (Pact) | High-value external consumers | Consumer buy-in, broker | When consumers won't maintain pacts |
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 treat the document as output of metadata plus the System.Text.Json contract, and check each symptom against its source:
ExcludeFromDescription, conventional MVC routes, no AddEndpointsApiExplorer with Swashbuckle, or a document's ShouldInclude filter.IResult; switch to TypedResults with Results<...>.[JsonPolymorphic] / [JsonDerivedType] to get oneOf with a discriminator.JsonStringEnumConverter for the API.required.Then I add a snapshot test of the document. The trade-off: fixing the source (types, JSON options) is more work than patching with transformers, but keeps the docs and the wire format in step.
How to tell it (STAR)
**S:** At [company] our customer API had [six] consumers and we caused [four] breaking-change incidents in one quarter. **T:** I was asked to stop surprises without freezing development. **A:** I made the build-time spec a committed artefact, split it into a frozen v1 and a v2, added drift, lint and oasdiff checks against both main and the last release, and agreed a compatibility policy with an explicit override label. **R:** In the next [two quarters] there were [zero] consumer-reported breaks, the check blocked [five] accidental ones, and the planned changes shipped in v2 with a clear deprecation timeline.
Last updated 23 Nov 2026.