Skip to content
Tutorials Center
My learning

Topics

Lesson 39 of 52 ยท Advanced Topics

OpenAPI, Documentation and API Versioning

Document ASP.NET Core APIs with OpenAPI endpoint metadata, pick a versioning strategy, and apply pagination and idempotency-key conventions with runnable code.

An API that nobody can learn to use is not much of an API. OpenAPI (formerly Swagger) is the standard, machine-readable way to describe an HTTP API: which paths exist, which methods they accept, what parameters and bodies they expect and what responses they return. From one OpenAPI document you can generate interactive documentation, client libraries in many languages, mock servers and contract tests.

Starting with .NET 9, ASP.NET Core ships its own OpenAPI support in the package Microsoft.AspNetCore.OpenApi, and .NET 10 refines it (OpenAPI 3.1 by default, YAML output, XML documentation comments). In this lesson you will learn where the document comes from, how to enrich it, how to version an API when it changes, and two conventions every public API needs: pagination and idempotency keys.

The OpenAPI package itself is a NuGet package that the single-file runner here does not have, so its calls are shown read-only. What is live is the thing it is built on: endpoint metadata. You will read that metadata yourself and generate a small OpenAPI-style document by hand, which makes the whole mechanism much less magical.

Where the document comes from

The framework does not parse your source code. Every endpoint carries a list of metadata objects (route pattern, HTTP methods, tags, response types and so on), and the OpenAPI generator walks that list. This is why the same metadata drives Swagger UIs, authorization and CORS (Route Groups and Organizing Endpoints introduced the idea).

flowchart LR
    A["Endpoint definitions<br/>MapGet, MapPost, ..."] --> B["Endpoint metadata<br/>tags, summary, produces"]
    B --> C["OpenAPI generator"]
    C --> D["openapi/v1.json"]
    D --> E["Docs UI"]
    D --> F["Generated clients"]
    D --> G["Contract tests"]

Metadata on endpoints is the single source for the document; tools downstream only read the JSON.

In a project that references the package, the setup is two lines. This code is read-only here:

C#
// Program.cs (needs the Microsoft.AspNetCore.OpenApi package)
builder.Services.AddOpenApi();            // registers the generator, document name "v1"

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.MapOpenApi();                     // serves /openapi/v1.json
}

MapOpenApi also serves YAML when you request a path ending in .yaml. The framework does not include a UI. Popular choices are Scalar and Swagger UI, which you add as separate packages and point at /openapi/v1.json.

Describing endpoints with metadata

The generator guesses a lot from your code: the route and method, parameters from the lambda or method signature, and request and response types from parameter and return types. When the return type is a union of TypedResults such as Results<Ok<Todo>, NotFound>, it even knows the status codes. You add the human parts with fluent calls:

Call Effect in the document
WithName("GetTodo") operationId, also used for link generation
WithTags("Todos") groups operations in the UI
WithSummary("...") / WithDescription("...") short title and longer text
Produces<T>(201) / ProducesProblem(404) extra documented responses
Accepts<T>("application/json") documented request body
ExcludeFromDescription() hides an internal endpoint

The following program defines a small API and then plays the generator's role: it reads every endpoint's metadata and prints an OpenAPI-style JSON document. It uses the same metadata interfaces the real generator reads.

C# Reading endpoint metadata to build an OpenAPI-style document

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Look at what the output contains that you never wrote by hand: the 200 and 404 responses of GetTodo come from its Results<Ok<Todo>, NotFound> return type, and the response type of ListTodos comes from the lambda's return type. /internal/ping is missing because it was excluded. A real document also describes JSON schemas for Todo, query parameters and request bodies, but the principle is identical.

Prefer TypedResults and Results<...> return types. They make the code self-describing, the compiler checks that you return only what you declared, and the OpenAPI document gets accurate status codes for free.

In .NET 10, XML documentation comments (/// <summary>) on your handler methods can also flow into summaries and descriptions when you enable GenerateDocumentationFile in the project file, so documentation can live next to the code it describes. For anything the fluent calls do not cover, document, operation and schema transformers (AddOpenApi(options => options.AddDocumentTransformer(...))) let you edit the generated document, for example to add security schemes or a server list. The older WithOpenApi helper was deprecated in .NET 10 in favor of transformers.

Versioning strategies

Sooner or later you must change an API in a way that breaks existing callers: rename a field, remove an endpoint, change a meaning. Versioning lets old and new callers coexist. There are four common styles:

Strategy Example Good Bad
URL path /v2/orders obvious, cache- and curl-friendly the "same" resource has several URLs
Query string /orders?api-version=2 one path easy to forget, caching surprises
Header X-Api-Version: 2 clean URLs invisible in a browser, harder to test
Media type Accept: application/vnd.shop.v2+json very RESTful complex for clients

Most public APIs choose the URL path: it is the easiest to understand and to route. Whatever you pick, a few rules help:

  • Add a version only for breaking changes. Adding an optional field or a new endpoint is not breaking.
  • Support at least the previous version for a deprecation period, and announce it (a Deprecation or Sunset response header is a good signal).
  • Keep the shapes per version in separate DTO types (DTOs, Records and Mapping) so a new version never accidentally changes an old response.

With route groups, URL versioning is simple: one group per version. The package Asp.Versioning.Http adds richer features (reading the version from several places, advertising supported versions), but is not needed for the basics. The example below supports both URL and header versioning: a small middleware reads an X-Api-Version header and rewrites an unversioned path into the versioned one before routing.

C# URL and header versioning with route groups

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The sample leaves "no version" as a 404 on purpose. Some APIs default to the oldest version so existing clients never break; others require an explicit version. Decide early and write it down, because changing the default is itself a breaking change.

Pagination conventions

Never return an unbounded list. A response with a million rows hurts the server, the network and the client. Two styles dominate:

  • Offset pagination (?page=3&pageSize=20 or ?offset=40&limit=20): easy, supports jumping to a page, but slow on large tables and unstable when rows are inserted while the client pages through.
  • Cursor pagination (?after=<opaque cursor>&limit=20): the server returns a cursor that encodes where the last item was. It is fast and stable, but you cannot jump to page 17.

Good conventions for either style: cap limit on the server, return the cursor or total in the body (or a Link header), and make cursors opaque (for example Base64 text) so clients do not depend on their internal structure.

Idempotency keys

A client that loses the response to POST /payments does not know whether the payment happened. Retrying risks charging twice. The standard solution is an idempotency key: the client generates a unique value per logical operation and sends it in an Idempotency-Key header. The server remembers the first result for that key, and a repeated request with the same key returns the stored result instead of repeating the work.

The next program implements both ideas. The list endpoint uses a cursor, and the payment endpoint stores results by key in a thread-safe dictionary (production code would use a database or distributed cache with an expiry).

C# Cursor pagination and idempotency keys

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Notice that the second call with order-1001 returns the same payment id and the counter shows only two real charges for three requests. A production implementation also checks that a repeated key comes with the same request body (otherwise it is a client bug and the answer is 422 or 409) and deletes old keys after a day or so.

Documentation habits that pay off

  • Give every operation a stable WithName; generated client method names come from it.
  • Document error responses, not only the happy path: ProducesProblem(404) tells client authors what to handle (Error Handling and Problem Details).
  • Serve the document only where it should be public. Many teams expose it in Development and publish it deliberately for production.
  • Treat the OpenAPI file as a contract: compare it in CI against the previous version to catch accidental breaking changes.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where does the OpenAPI generator get most of its information about your endpoints?

    Each endpoint carries a metadata list (route, methods, tags, produced responses and more). The generator walks that list, which is also what authorization and CORS use.
  2. 2. Which return type gives the OpenAPI document accurate status codes automatically?

    A union of TypedResults declares every possible response, so the status codes and body types can be read from the signature.
  3. 3. A client times out on POST /payments and retries. How do you prevent a double charge?

    An idempotency key identifies the logical operation. The server stores the first outcome and returns it again for repeats, so the work happens once.
  4. 4. What is the main advantage of cursor pagination over offset pagination?

    A cursor records where the previous page ended, so the database does not skip over rows and new rows do not shift pages. The trade-off is that you cannot jump to an arbitrary page.

Summary

  • OpenAPI describes an HTTP API in a machine-readable document; .NET generates it from endpoint metadata with AddOpenApi and MapOpenApi (package Microsoft.AspNetCore.OpenApi).
  • Enrich the document with WithName, WithTags, WithSummary, Produces, ProducesProblem and prefer TypedResults return types.
  • Version only for breaking changes; URL-path versioning with one route group per version is the simplest and most common choice.
  • Always paginate lists, cap the page size and keep cursors opaque.
  • Use an Idempotency-Key header so retried POST requests do not repeat side effects.

Next: Rate Limiting, Health Checks and Resilience of the App