An API rarely stays the same throughout its lifetime. A development team may add a new endpoint, rename a request property, introduce a response status code, change authentication requirements, or modify an existing response model.
These changes affect more than the application code. They also affect the API contract that frontend developers, mobile applications, external integrations, and other services depend on.
OpenAPI provides a standard way to describe that contract. It documents available endpoints, HTTP methods, request parameters, request and response schemas, authentication requirements, and possible response codes.
The problem is that API implementations and their documentation can become inconsistent. A developer may update an endpoint but forget to update a manually maintained OpenAPI file. Another developer may change a response model without realizing that a generated client depends on the previous schema.
ASP.NET Core provides built-in OpenAPI generation through Microsoft.AspNetCore.OpenApi. It can generate documentation from API metadata, customize the generated document through transformers, and generate documents during the build process.
These capabilities make it possible to keep API documentation closer to the actual implementation and detect contract changes before they reach production.
Why OpenAPI Documentation Becomes Outdated
Consider an ASP.NET Core application that exposes an endpoint for retrieving customer information.
Initially, the endpoint returns a customer ID, name, and email address.
public record CustomerResponse(
int Id,
string Name,
string Email);
The endpoint might look like this:
app.MapGet("/customers/{id:int}", async (
int id,
CustomerService service) =>
{
var customer = await service.GetByIdAsync(id);
return customer is null
? Results.NotFound()
: Results.Ok(customer);
});
Later, the development team changes the response model to include the customer's account status.
public record CustomerResponse(
int Id,
string Name,
string Email,
string AccountStatus);
If the OpenAPI document is maintained separately, someone must remember to update the response schema.
Otherwise, the documentation continues describing the old response even though the application returns additional information.
Similar problems occur when:
A new endpoint is introduced without being added to the API specification.
A response changes from 200 OK to include additional error responses.
A request property becomes required.
A query parameter is renamed or removed.
Authentication requirements change.
An endpoint is deprecated but remains documented as the preferred option.
Generated OpenAPI documentation reduces this maintenance burden because ASP.NET Core can derive much of the contract from endpoint definitions, parameter types, response metadata, and other API information.
However, generation alone does not guarantee complete documentation. Developers still need to provide meaningful descriptions, declare important response scenarios, and customize information that cannot be inferred from the implementation.
Enabling Built-In OpenAPI Generation
ASP.NET Core includes built-in OpenAPI generation through the Microsoft.AspNetCore.OpenApi package.
For a project that does not already reference the package, install it using the .NET CLI:
dotnet add package Microsoft.AspNetCore.OpenApi
Next, register OpenAPI services in Program.cs:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddOpenApi();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.MapOpenApi();
}
app.MapGet("/", () => "Customer API");
app.Run();
The AddOpenApi method registers the services required to generate the OpenAPI document.
The MapOpenApi method exposes the generated document through an HTTP endpoint.
By default, the document is available at:
https://localhost:{PORT}/openapi/v1.json
Replace the port with the application's actual development port.
When the application starts, ASP.NET Core generates the document using the available API descriptions and metadata.
The important advantage is that developers do not need to manually maintain a separate list of endpoints and request models.
The generated document can reflect changes to the API implementation, provided those changes are represented by metadata that the OpenAPI generator understands.
OpenAPI generation does not automatically include an interactive API interface. If developers need Swagger UI or Scalar, those tools must be configured separately.
Describing API Changes With Endpoint Metadata
Generated documentation is only useful when it explains what an endpoint actually does.
Consider an endpoint that creates a customer:
app.MapPost("/customers", async (
CreateCustomerRequest request,
CustomerService service) =>
{
var customer = await service.CreateAsync(request);
return Results.Created(
$"/customers/{customer.Id}",
customer);
});
The endpoint communicates its route and request type, but additional metadata can make the generated document more useful.
ASP.NET Core provides methods such as WithName, WithSummary, WithDescription, Produces, and Accepts.
A more descriptive endpoint looks like this:
app.MapPost("/customers", async (
CreateCustomerRequest request,
CustomerService service) =>
{
var customer = await service.CreateAsync(request);
return Results.Created(
$"/customers/{customer.Id}",
customer);
})
.WithName("CreateCustomer")
.WithSummary("Create a customer")
.WithDescription(
"Creates a customer account using the supplied customer information.")
.Produces<CustomerResponse>(
StatusCodes.Status201Created)
.ProducesProblem(
StatusCodes.Status400BadRequest);
Each method contributes information to the generated OpenAPI operation.
WithName provides an operation identifier that can be useful to client-generation tools.
WithSummary and WithDescription explain the endpoint's purpose.
Produces declares a response type and status code, while ProducesProblem describes a problem-details response.
This is especially important when the endpoint can return multiple response types or status codes that are not obvious from static analysis.
The same principle applies to request models. Property names, types, nullability, validation metadata, and JSON serialization settings can influence the generated schema.
For example:
public record CreateCustomerRequest
{
public required string Name { get; init; }
public required string Email { get; init; }
public string? PhoneNumber { get; init; }
}
When the request model changes, the generated schema can reflect the updated structure.
Developers should still verify how required and optional properties are represented, particularly when using custom JSON converters, nullable reference types, or serializer configuration.
Using OpenAPI Transformers to Customize Generated Documents
Some API information applies to individual endpoints, while other information applies to the entire document.
For example, an application may need to add a standard API title, description, contact information, or authentication configuration.
ASP.NET Core provides three transformer categories:
Document transformers modify the complete OpenAPI document.
Operation transformers modify individual endpoint operations.
Schema transformers modify request and response schemas.
These transformers are useful when the default generated document needs additional information.
Adding document-level information
A document transformer can define the API's title, version, and description.
using Microsoft.AspNetCore.OpenApi;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddOpenApi(options =>
{
options.AddDocumentTransformer((document, context, cancellationToken) =>
{
document.Info = new()
{
Title = "Customer Management API",
Version = "v1",
Description =
"API for managing customer accounts and information."
};
return Task.CompletedTask;
});
});
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.MapOpenApi();
}
app.MapGet("/customers", () => Results.Ok());
app.Run();
The transformer runs when ASP.NET Core generates the document.
This is a useful place to maintain metadata that applies to the entire API rather than repeating it across individual endpoints.
Adding common response information
An application may have a standard internal server error response that should appear across its documented operations.
An operation transformer can add this information consistently:
using Microsoft.AspNetCore.OpenApi;
using Microsoft.OpenApi;
builder.Services.AddOpenApi(options =>
{
options.AddOperationTransformer(
(operation, context, cancellationToken) =>
{
operation.Responses ??= new OpenApiResponses();
operation.Responses.TryAdd(
"500",
new OpenApiResponse
{
Description = "Internal server error"
});
return Task.CompletedTask;
});
});
This example adds a response description to each generated operation.
In a production application, the response should also describe the actual error representation if the API returns a structured error body.
Do not add response codes simply because they are theoretically possible. Document the responses that the application actually supports.
Updating generated schemas
Schema transformers are useful when a particular C# type needs additional OpenAPI metadata.
For example, a decimal property might need a specific schema format for downstream tools.
builder.Services.AddOpenApi(options =>
{
options.AddSchemaTransformer(
(schema, context, cancellationToken) =>
{
if (context.JsonTypeInfo.Type == typeof(decimal))
{
schema.Format = "decimal";
}
return Task.CompletedTask;
});
});
This transformer applies to decimal schemas generated by the application.
It is particularly useful when a team needs consistent schema conventions across multiple request and response models.
Transformers execute in a defined order: schema transformers run during schema registration, operation transformers run while operations are added, and document transformers run after the operations and schemas have been processed.
Understanding this order helps when one customization depends on another.
Generating Multiple OpenAPI Documents
Some applications expose different API surfaces for different consumers.
For example, a customer management application might expose public endpoints to external clients and internal endpoints for administrative services.
Publishing every endpoint in a single document may not be appropriate.
ASP.NET Core supports generating multiple OpenAPI documents from one application.
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddOpenApi("public");
builder.Services.AddOpenApi("internal");
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.MapOpenApi();
}
app.MapGet("/customers", () => Results.Ok())
.WithGroupName("public");
app.MapGet("/admin/reports", () => Results.Ok())
.WithGroupName("internal");
app.Run();
The generated documents can be accessed separately:
/openapi/public.json
/openapi/internal.json
The default document name is v1 when AddOpenApi is called without a name.
For more controlled grouping, configure the ShouldInclude option for each document so that endpoints are included according to the application's grouping rules.
This approach is useful when different teams or clients need different API contracts.
However, separating documentation does not replace authorization. An endpoint must still enforce access controls independently of whether it appears in a public or internal OpenAPI document.
Generating OpenAPI Documents During the Build
Runtime generation is useful when an application exposes its OpenAPI document directly.
However, some teams prefer to generate the document during the build process.
This is particularly useful when:
API specifications are committed to source control.
Frontend or mobile teams generate clients from the specification.
CI pipelines validate API contract changes.
Documentation is hosted separately from the running application.
Integration tests need a stable OpenAPI artifact.
ASP.NET Core supports build-time generation through the Microsoft.Extensions.ApiDescription.Server package.
Install the package:
dotnet add package Microsoft.Extensions.ApiDescription.Server
Then configure the project file:
<PropertyGroup>
<OpenApiGenerateDocumentsOnBuild>true</OpenApiGenerateDocumentsOnBuild>
<OpenApiDocumentsDirectory>$(MSBuildProjectDirectory)</OpenApiDocumentsDirectory>
</PropertyGroup>
With this configuration, the build process can generate the OpenAPI document and place it in the configured directory.
For a project that generates documentation as part of CI, this makes the specification available without starting the application and requesting its OpenAPI endpoint.
Build-time generation is particularly valuable when the specification is treated as a versioned artifact.
For example, a team can review changes to the generated JSON file in a pull request before merging changes to the API implementation.
It is important to keep the generated document and application code synchronized. If a specification is committed to source control, regenerate it whenever the API contract changes.
Detecting API Contract Changes in CI
Generating OpenAPI documentation is only one part of keeping it accurate.
A reliable workflow should also detect unexpected changes before deployment.
Consider a pull request that removes a response property used by a mobile application.
The API may compile successfully, and its unit tests may pass, but the change can still break existing clients.
A CI pipeline can reduce this risk by generating the OpenAPI document and comparing it with the previously approved contract.
A typical workflow looks like this:
Developer updates an API endpoint
|
v
Build the API project
|
v
Generate the OpenAPI document
|
v
Compare with the approved contract
|
v
Check for breaking changes
|
+------+------+
| |
v v
No breaking Breaking
changes changes
| |
v v
Continue CI Review or reject
the API change
A contract comparison tool can identify changes such as removed endpoints, renamed properties, changed parameter types, or incompatible response modifications.
The exact compatibility rules depend on the tool and the API's versioning policy.
Not every OpenAPI document change is breaking. Adding an optional response property may be compatible for many clients, while changing a required request property can break existing integrations.
Teams should establish explicit rules for how contract changes are reviewed and approved.
For example, an API team might allow compatible additions in the current version while requiring a new API version for incompatible changes.
Build-time generation makes this process easier because the specification becomes a repeatable build artifact rather than a document that someone must update manually.
Choosing the OpenAPI Version
OpenAPI specifications evolve, and downstream tools do not always support the same versions.
The built-in ASP.NET Core OpenAPI generator supports OpenAPI 3.1 starting with .NET 10 and OpenAPI 3.2 starting with .NET 11.
The default generated version is 3.1 in .NET 10 and 3.2 in .NET 11.
If a client-generation tool or API gateway does not yet support the newer specification, explicitly select a compatible version.
For example, to generate an OpenAPI 3.1 document:
using Microsoft.OpenApi;
builder.Services.AddOpenApi(options =>
{
options.OpenApiVersion = OpenApiSpecVersion.OpenApi3_1;
});
Choosing a specification version should be part of the API tooling strategy.
Before upgrading the OpenAPI version, verify compatibility with client generators, API gateways, testing tools, and documentation platforms.
A newer specification does not automatically mean every downstream tool can consume it.
Common Mistakes to Avoid
Even with built-in generation, a few mistakes can make OpenAPI documentation unreliable.
Assuming generated documentation is always complete
ASP.NET Core can infer information from endpoint signatures and metadata, but it cannot automatically understand every business rule or operational behavior.
Declare important response codes, descriptions, authentication requirements, and endpoint behavior explicitly.
Forgetting to update API metadata
Changing an endpoint implementation without reviewing its OpenAPI metadata can leave incomplete descriptions or incorrect response information.
Treat documentation metadata as part of the endpoint implementation.
Exposing internal endpoints unintentionally
If an application generates separate public and internal documents, configure endpoint inclusion carefully.
Also enforce authorization at runtime. OpenAPI grouping is not a security boundary.
Ignoring breaking contract changes
A generated document can be syntactically valid while still breaking existing clients.
Use contract comparison and compatibility checks in CI rather than relying only on successful compilation.
Assuming an interactive UI is included
The built-in OpenAPI package generates the specification. It does not automatically provide Swagger UI or Scalar.
Configure an interactive interface separately if developers need to explore and test endpoints through a browser.
Summary
Keeping OpenAPI documentation synchronized with ASP.NET Core APIs becomes easier when the specification is generated from the application rather than maintained independently.
Microsoft.AspNetCore.OpenApi provides runtime document generation, endpoint metadata, and document, operation, and schema transformers. Applications can also generate separate documents for different API groups.
For teams that want stronger control over API contracts, build-time generation through Microsoft.Extensions.ApiDescription.Server makes the OpenAPI document available during the build process.
The next important step is integrating contract validation into CI. Comparing generated specifications with approved contracts helps identify potentially breaking changes before they reach consumers.
OpenAPI should be treated as part of the API development process, not as documentation that gets updated only when someone remembers. When endpoint changes, schema updates, and contract checks are part of the same workflow, API documentation becomes more reliable for every team that depends on it.
Join the conversation! Your thoughts help the community grow.