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

📚 Interview question

How would you use the OpenAPI document as a contract in CI? Explain how you detect breaking changes between versions with a tool like oasdiff, lint the spec, and manage separate documents for each major API version.

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.

Senior Architecture Advanced api-contracts api-versioning aspnet-core breaking-changes ci-cd openapi

🎯 Key points

  • Committed build-time spec is the contract; CI regenerates it and fails on drift
  • oasdiff breaking base revision --fail-on ERR compares the PR spec with main (and with the last released spec) and classifies changes by severity
  • Typical breaking changes: removed path or property, new required request field, removed enum value, changed type; a response property becoming nullable breaks strongly typed clients that assume a value
  • Spectral lints structure and style: valid OpenAPI, operationId present, ProblemDetails for errors, naming conventions, no undocumented 2xx; a shared ruleset scales the rules across teams
  • One document per major version (AddOpenApi("v1"), AddOpenApi("v2") with ShouldInclude by group name or Asp.Versioning); additive changes stay in the current version
  • Written compatibility policy: breaking change only through a new major version, a deprecation period with Deprecation/Sunset headers, consumer notice and an explicit reviewed override label
  • Spec diffs catch shape changes; consumer-driven contract tests (Pact) catch behaviour consumers depend on; use both where consumers are external

⏱ 30-second 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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 breaking classifies every change, and with --fail-on ERR the 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-approved label 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."


The pipeline

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)

Breaking or not?

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

Versioned documents

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

Production example

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.

🔍 What the interviewer is checking

Checks that the candidate can design a contract governance process, not just generate a document.

Green flags

  • Commits the spec and checks drift.
  • Uses a breaking-change tool against both main and the released version.
  • Knows request versus response asymmetry of breaking changes.
  • Freezes major versions and has an explicit override process.
  • Knows where spec diffs stop and contract tests begin.

Red flags

  • Relies on reviewers reading JSON diffs.
  • Thinks adding a URL version prefix is enough.
  • Creates new versions for every change, or never.

📚 Learn in depth

1. Why the spec is a good contract artefact

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.

2. How oasdiff decides

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.
  • The last released spec (tag or artefact): catches breaks accumulated across several merged PRs before a release.

3. Linting

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.

4. Versioned documents in ASP.NET Core

  • Built-in generator: 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.
  • With Asp.Versioning (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.
  • Freeze rule: once v1 is released, its document only accepts additive changes. Breaking work goes into v2.

5. Where spec checks stop

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.

Try it yourself

  1. Install oasdiff, copy your spec, remove a response property in the copy and run oasdiff breaking old.json new.json.
  2. Make a request property required and see which rule fires.
  3. Add a Spectral ruleset requiring operationIds and run it against your spec.
  4. Register AddOpenApi("v1") and AddOpenApi("v2") with route groups using WithGroupName and compare the two files.
  5. Add the oasdiff step to a GitHub Actions workflow and make it post the changelog as a PR comment.

💻 Code

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

⚠ Common mistakes

  • Mistake: Comparing only with 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.
  • Mistake: Versioning URLs but letting v1's document change freely. Why it is wrong: The version number promises stability the contract doesn't keep. Instead: Freeze released major versions to additive changes and enforce it with oasdiff.
  • Mistake: Treating every new response property as safe. Why it is wrong: Clients with strict deserialisation or exhaustive enum handling can break. Instead: Know your consumers; document the compatibility policy ("clients must ignore unknown fields").
  • Mistake: Making the breaking-change check advisory only. Why it is wrong: Warnings get ignored under deadline pressure. Instead: Fail the build; allow an explicit, reviewed override label.
  • Mistake: Relying on CI to tell consumers about changes. Why it is wrong: A passing pipeline doesn't mean consumers know a deprecation or a new version is coming, so they find out when v1 is switched off. Instead: Publish the oasdiff changelog in release notes, send deprecation notices with dates, return Deprecation and Sunset headers, and track which consumers still call old versions.
  • Mistake: Running checks against a spec downloaded from a dev server. Why it is wrong: It may not match the PR's code. Instead: Generate at build time and check the committed file.
  • Mistake: Relying on the spec diff alone for critical consumers. Why it is wrong: It can't detect semantic or behavioural changes. Instead: Add consumer-driven contract tests for those consumers.
  • Mistake: Creating a new major version for every small change. Why it is wrong: Each live version is code to run, test and secure. Instead: Prefer additive evolution; reserve new versions for genuine breaks, with a published deprecation and sunset date.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions comparing the PR spec with main. Why: Checks how the committed spec is produced in the first place.
    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 assumes the generated document is correct. Why: Checks that the spec is accurate enough to be trusted as a contract.
    How to answer

    I treat the document as output of metadata plus the System.Text.Json contract, and check each symptom against its source:

    • Missing endpoints: is it in API Explorer? Common causes are ExcludeFromDescription, conventional MVC routes, no AddEndpointsApiExplorer with Swashbuckle, or a document's ShouldInclude filter.
    • No response schema: the handler returns IResult; switch to TypedResults with Results<...>.
    • Polymorphism: add [JsonPolymorphic] / [JsonDerivedType] to get oneOf with a discriminator.
    • Enums as integers: register JsonStringEnumConverter for the API.
    • Nullability: enable nullable reference types and use 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.

🛠 Real-world problems: how you handle them

Consumer teams kept discovering breaking changes in production
Situation
A [shared customer] API on .NET 10 with [six] consumer teams (web, mobile, two internal services, two partners), released [weekly] to Azure App Service in Australia East.
Signals
[Four] incidents in a quarter traced to response shape changes; partner tickets citing missing fields; teams pinning to old builds; release notes that didn't mention API changes.
Investigation
Diffed the released specs for the last [12] releases with oasdiff and found [9] breaking changes, none labelled; checked the process and found no committed spec, no versioned documents and no compatibility policy.
Resolution
Immediately restored the two removed fields partners depended on. Then committed build-time specs, split documents into a frozen v1 and a new v2, added drift, Spectral and oasdiff checks against main and the last release tag, and required a labelled, reviewed override for any intentional break.
Prevention
CI contract job on every pull request; a written compatibility policy (additive in place, breaking only in a new major with a 6-month deprecation and `Sunset` header); oasdiff changelog published in release notes; Pact tests for the two partners.

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.

↩ Usually asked after

More in API Features

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me