Start With the Code as the Contract

For an internal API with one caller that ships alongside it, the code is the contract, and a formal spec is extra work. A spec earns its place when other people integrate from your documentation, because from then on what you published and what you run have to agree.

A partner regenerates their client from your published spec and their integration breaks: the response field they use was renamed two releases ago, and the spec never caught up. Hand-maintained API docs drift from code in exactly this way, one forgotten edit at a time.

OpenAPI 3.1 describes every endpoint, parameter, response and error in a format tools can read, so docs, clients and tests can all come from it. That only works if the spec stays true. Below is how to generate it from code (or the other way round), lint it for usefulness, and fail the build on breaking changes before a partner finds them.

Signs your spec has drifted
  • Your "OpenAPI doc" is a stale Notion page
  • Three teams have hand-written three different SDKs for the same API
  • Your spec lies — the API actually returns a different shape
  • You're on an old Swashbuckle release that can only emit OpenAPI 2.0 or 3.0

What OpenAPI Gives You

  • Code-first — write C#, generate the spec. Fast iteration, spec follows code.
  • Spec-first — write the spec, generate stubs. Better for cross-team contracts.
  • Hybrid — generate from code, then lint/diff in CI to catch breaking changes.

flowchart LR
    Code[".NET 10 endpoints<br/>+ XML docs"] --> Gen["AddOpenApi()<br/>MapOpenApi()"]
    Gen --> Spec["openapi.json<br/>(OpenAPI 3.1)"]
    Spec --> UI["Scalar UI<br/>or Redoc"]
    Spec --> Sdk["Kiota / NSwag<br/>typed SDKs"]
    Spec --> Lint["Spectral lint<br/>+ openapi-diff in CI"]
    Spec --> AI["AI agents<br/>(tool calling)"]

    style Spec fill:#85EA2D,color:#000,stroke:#3aa31d

Generating, Linting and Diffing a Spec

Step 1: Enable .NET 10 built-in OpenAPI

// .csproj
// <PropertyGroup>
//   <GenerateDocumentationFile>true</GenerateDocumentationFile>
//   <NoWarn>$(NoWarn);1591</NoWarn>
// </PropertyGroup>

builder.Services.AddOpenApi("v1", o =>
{
    o.AddDocumentTransformer((doc, ctx, ct) =>
    {
        doc.Info.Title       = "Orders API";
        doc.Info.Version     = "v1";
        doc.Info.Description = "Order management endpoints.";
        return Task.CompletedTask;
    });
});

var app = builder.Build();
app.MapOpenApi("/openapi/{documentName}.json");   // serves the spec
✅

Check it: Fetch the generated document and compare one endpoint with what the service really returns. They should match field for field.

Step 2: Document endpoints (Minimal API)

// TypedResults + a Results<...> union is the .NET 10 idiom: the delegate's
// return type IS the OpenAPI response shape — no .Produces<T>() needed.
app.MapGet("/orders/{id:long}", async Task<Results<Ok<OrderDto>, NotFound>> (long id, IOrderRepo repo) =>
{
    var o = await repo.FindAsync(id);
    return o is null ? TypedResults.NotFound() : TypedResults.Ok(o);
})
.WithName("GetOrder")
.WithSummary("Get an order by id")
.WithDescription("Returns a single order. 404 if not found.")
.WithTags("Orders");

// XML doc comments only count on types and members, not on a MapPost call,
// so describe lambda endpoints with WithSummary / WithDescription.
app.MapPost("/orders", async Task<Results<Created<OrderDto>, ValidationProblem>> (CreateOrderCmd cmd, IOrderRepo repo) =>
{
    var order = await repo.CreateAsync(cmd);
    return TypedResults.Created($"/orders/{order.Id}", order);
})
   .WithName("CreateOrder")
   .WithSummary("Place a new order")
   .WithDescription("Total must be > 0. Idempotency-Key header is required.")
   .WithTags("Orders");
✅

Check it: Find an endpoint that can return an error and look for that error in the spec. If only the success response is documented, generated clients will treat every failure the same way.

Step 3: Render with Scalar (modern Swagger UI replacement)

// dotnet add package Scalar.AspNetCore

if (app.Environment.IsDevelopment())
{
    app.MapOpenApi();   // only if you didn't already map it in Step 1
    app.MapScalarApiReference("/docs", o =>
    {
        o.WithTitle("Orders API")
         .WithTheme(ScalarTheme.Purple)
         .WithDefaultHttpClient(ScalarTarget.CSharp, ScalarClient.HttpClient);
    });
}
// Browse to /docs — dark mode, and request snippets for more than 20 client targets.

Step 4: Schema transformers for cross-cutting concerns

builder.Services.AddOpenApi(o =>
{
    // Add Bearer auth scheme to every operation
    o.AddDocumentTransformer<BearerSecuritySchemeTransformer>();

    // Treat all DateTimeOffset as ISO-8601 strings with examples
    o.AddSchemaTransformer((schema, ctx, ct) =>
    {
        if (ctx.JsonTypeInfo.Type == typeof(DateTimeOffset))
            schema.Example = JsonValue.Create("2026-04-01T12:00:00Z"); // .NET 10 uses JsonNode, not OpenApiAny
        return Task.CompletedTask;
    });
});

Step 5: Generate typed SDKs with Kiota

// Microsoft Kiota: C#, Go, Java, PHP, Python, Ruby and TypeScript
// kiota generate -l csharp -d https://api.example.com/openapi/v1.json \
//                -c OrdersClient -n Example.Orders.Client -o ./Generated

// Usage:
var http = new HttpClient { BaseAddress = new Uri("https://api.example.com") };
var auth = new BaseBearerTokenAuthenticationProvider(new TokenProvider());
var adapter = new HttpClientRequestAdapter(auth, httpClient: http);
var client  = new OrdersClient(adapter);
var order   = await client.Orders[42].GetAsync();   // strongly typed
✅

Check it: Generate a client and read the method names. If they look machine-made, the endpoints are missing operation names.

Step 6: Lint + diff in CI (catch breaking changes)

# .github/workflows/api.yml
# Microsoft.Extensions.ApiDescription.Server writes the spec during dotnet build
# (OpenApiDocumentsDirectory sets where; the file is named after the project)
# - run: dotnet build Api
# - uses: stoplightio/spectral-action@latest      # style + correctness lint
#   with:
#     file_glob: 'Api/Api.json'
# - uses: oasdiff/oasdiff-action/breaking@v0      # breaking-change detection
#   with:
#     base: 'origin/main:Api/Api.json'
#     revision: 'HEAD:Api/Api.json'
#     fail-on: ERR
# Result: PR fails if a contract-breaking change ships without a version bump.
✅

Check it: Rename a response field in a branch and open a pull request. The build should fail, and say which field changed.

Design-First or Code-First

Everything above is code-first: the spec is generated from the running application. The alternative is design-first, where the team writes or edits the spec, reviews it with the people who will call the API, and only then implements it. Both work; they suit different situations.

  • Code-first fits internal APIs owned by one team, where the fastest feedback loop is changing code and seeing the spec update. Its risk is that the API’s shape becomes whatever the DTOs happened to look like.
  • Design-first fits partner-facing and public APIs, where agreeing the contract before anyone writes code is cheaper than changing it after partners have integrated. Its risk is drift in the other direction: code that no longer matches the agreed spec.

A hybrid works well in practice. Generate the spec from code, commit the generated file to the repository, and review its diff in every pull request like any other code. Reviewers then see “this change renames a response field” directly, without reading the handler, and API design becomes part of code review rather than a separate ceremony.

Proving the Service Matches the Spec

A generated spec describes what the code declares. It does not prove what the code returns: a handler can declareOrderDto and serialise something slightly different through a custom converter. Two checks close that gap. In integration tests, validate every response against the spec’s schema, so a test fails when the real payload stops matching. And run a spec-driven fuzzer such as Schemathesis against a test deployment; it generates requests from the spec, including edge cases nobody writes by hand, and reports responses that violate the declared status codes or schemas, including undocumented 500s.

✅

Check it: Run a spec-driven fuzzer against a test deployment and read what it reports. Undocumented 500s and responses that don't match their schema are the gaps between your spec and your service.

Specs That AI Agents Can Use

Agents and assistants increasingly call APIs by reading their OpenAPI documents as tool definitions. The spec then is the prompt. Thesummary and description of each operation are what the model reads when deciding which call to make, so write them for that reader: what the operation does, when to use it rather than a similar one, and what the important parameters mean. Use enums instead of free-text strings wherever the values are known, add an example for every request body, and keep operations narrow. One endpoint with a dozen optional modes is hard for a person to use and harder for a model.

How Specs Drift

  1. Hand-written specs that drift. If the spec isn't generated from (or validated against) the running code, it will lie within a sprint. Either generate or contract-test.
  2. No operationId. Generated SDK method names become GetUsers_2_post_v3(). Set.WithName("CreateOrder") on every endpoint.
  3. Missing error schemas. A spec that only documents the happy path produces SDKs that throwApiException for everything. Document application/problem+json for 4xx/5xx. A Results<...> union return type (Step 2) declares each status code for you, but only problem types such as ValidationProblem carry a problem+json body (a bare NotFound has none), and 5xx still needs ProducesProblem(500).
  4. Inline schemas everywhere. Same shape repeated across 12 endpoints = 12 generated types. Use$ref / shared DTOs.
  5. Ignoring breaking-change detection. Renaming a field is a breaking change even if your tests still pass. Runoasdiff in CI.
  6. Still on OpenAPI 2 / Swashbuckle 5. 3.0 added nullable and oneOf/anyOf; 3.1 goes further and aligns the Schema Object with JSON Schema 2020-12 (type: ["string", "null"] replaces nullable) and adds webhooks. .NET 10 emits 3.1 by default.

Try It on Your Own System This Week

Three checks on an API with a published spec, about an hour in total:

  1. Compare the published spec with production. Pick three endpoints and call them. Note every difference.
  2. Count the hand-written clients. Each one is a copy of the contract that can be wrong.
  3. Look for a diff step in CI. If nothing compares the new spec with the old one, a rename will reach partners unannounced.

What I Would Set Up First

  • .NET has built-in OpenAPI since .NET 9 — drop Swashbuckle from new projects.
  • Render with Scalar or Redoc; both beat the classic Swagger UI.
  • Set WithName on every endpoint. Prefer TypedResults with a Results<...> union return type over Produces<T> / ProducesProblem chains — the compiler keeps the spec honest instead of you.
  • Generate clients with Kiota, or NSwag if you emit OpenAPI 3.0 (its README lists Swagger 2.0 and OpenAPI 3.0) — never hand-write SDKs.
  • Document errors with application/problem+json (RFC 9457).
  • Lint specs with Spectral; diff against baseline with oasdiff in CI.
  • OpenAPI 3.1 + JSON Schema 2020-12 is the format AI agents read for tool-calling — keep it accurate.

OpenAPI 3.2 and Arazzo

OpenAPI 3.2, released in September 2025, added hierarchical tags, streaming media types and the QUERY method. Check your tooling's support before you move, since generators and validators lag behind the spec. Arazzo, from the same initiative, describes multi-step workflows across calls, which is useful for documenting a sequence that an agent or a developer has to follow.