Introduction
When an ASP.NET Core application exposes an API, frontend applications and other services often consume it through HTTP requests. These consumers may be written in C#, TypeScript, JavaScript, Java, Swift, or other programming languages.
Maintaining API communication manually becomes difficult as an application grows. A developer might rename a property, add a required request parameter, change a response type, or introduce a new endpoint. Every consumer that depends on the API must understand those changes.
OpenAPI helps solve this problem by providing a machine-readable description of an HTTP API. Tools such as NSwag and OpenAPI Generator can use that description to generate client classes, request models, and API methods.
However, generating a client once does not guarantee that it will remain synchronized with the server.
Consider this situation:
An ASP.NET Core API exposes a GetCustomer endpoint.
A developer changes the response model by adding a new property.
The backend is updated and deployed.
The frontend continues using an older generated client.
The application now has different expectations on the server and client sides.
The problem is not necessarily that code generation failed. The problem is that the generated client was not regenerated when the API contract changed.
The solution is to make OpenAPI generation and client generation part of the development and continuous integration workflow.
This article explains how to generate OpenAPI documents from ASP.NET Core, create strongly typed API clients, detect outdated generated code, and prevent contract drift through automated validation.
Understanding API Contract Drift
An API contract defines how a client communicates with a server. It describes information such as:
Available HTTP endpoints.
Supported HTTP methods.
Request parameters and request bodies.
Response structures and status codes.
Data types and validation requirements.
Authentication requirements.
Nullable and required properties.
For example, consider an endpoint that returns customer information.
public sealed class CustomerResponse
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public string Email { get; set; } = string.Empty;
}
The API might expose the following endpoint:
app.MapGet("/api/customers/{id:int}",
(int id) =>
{
var customer = new CustomerResponse
{
Id = id,
Name = "John",
Email = "[email protected]"
};
return Results.Ok(customer);
});
An OpenAPI document describes this endpoint and its response schema. A client generator can use that document to produce a C# client method and a corresponding model.
Now suppose the backend introduces a new property:
public sealed class CustomerResponse
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public string Email { get; set; } = string.Empty;
public string PhoneNumber { get; set; } = string.Empty;
}
The server now returns additional information, but an existing generated client might not contain the PhoneNumber property.
Depending on the serializer and client implementation, the application might continue working while silently ignoring the new field.
A more serious problem occurs when a property is renamed, a required parameter is added, or a response type changes. Existing clients may fail to compile or encounter runtime errors.
This situation is known as API contract drift.
Contract drift can happen in several ways:
The server changes without regenerating client code.
The OpenAPI document is updated manually instead of being generated from the application.
Different developers use different client generator versions.
Generated clients are committed to source control but are not checked during pull requests.
The API document describes different behavior from the actual endpoint.
A client is generated from a development API that does not match the contract intended for production.
The objective is to establish one reliable contract generation process and validate it whenever the API changes.
Understanding the OpenAPI Generation Process in ASP.NET Core
ASP.NET Core provides built-in OpenAPI support through the Microsoft.AspNetCore.OpenApi package.
The package generates an OpenAPI document from the application's endpoint metadata. It supports both controller-based APIs and Minimal APIs.
An OpenAPI document can be generated at runtime or during the application build process.
The runtime approach exposes the document through an HTTP endpoint. The build-time approach generates the document as part of the build, which is particularly useful for automated client generation.
Configuring OpenAPI in an ASP.NET Core application
Start by installing the OpenAPI package:
dotnet add package Microsoft.AspNetCore.OpenApi
Configure 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("/api/customers/{id:int}",
(int id) =>
{
var customer = new CustomerResponse
{
Id = id,
Name = "John",
Email = "[email protected]"
};
return Results.Ok(customer);
});
app.Run();
The AddOpenApi() method registers the services required to generate the document.
The MapOpenApi() method exposes the generated document through an HTTP endpoint.
By default, the document is available at:
https://localhost:5001/openapi/v1.json
The actual port depends on the application's configuration.
You can open this endpoint in a browser or download the JSON document using a command-line tool.
curl https://localhost:5001/openapi/v1.json -o openapi.json
The resulting JSON file describes the API contract.
It is important to understand that OpenAPI document generation and interactive documentation interfaces are separate concerns. The built-in package generates the document; a user interface such as Swagger UI or Scalar requires additional tooling.
Generating multiple OpenAPI documents
A single ASP.NET Core application may expose multiple API versions or separate public and internal APIs.
You can register multiple OpenAPI documents:
builder.Services.AddOpenApi("v1");
builder.Services.AddOpenApi("v2");
Each document can include a different set of endpoints using the ShouldInclude configuration.
For example:
builder.Services.AddOpenApi("v1", options =>
{
options.ShouldInclude = description =>
description.GroupName == "v1";
});
builder.Services.AddOpenApi("v2", options =>
{
options.ShouldInclude = description =>
description.GroupName == "v2";
});
Endpoints can be assigned to groups:
app.MapGet("/api/v1/customers",
() => Results.Ok("Customer API V1"))
.WithGroupName("v1");
app.MapGet("/api/v2/customers",
() => Results.Ok("Customer API V2"))
.WithGroupName("v2");
Map the documents:
app.MapOpenApi();
The application can now expose separate documents for different API versions.
Keeping these documents separate is useful when multiple client applications consume different API versions.
Generating OpenAPI Documents During the Build
Generating an OpenAPI document at runtime works well for local development and interactive documentation.
However, an automated client-generation workflow should not depend on a developer manually starting the API, downloading a document, and generating client code.
ASP.NET Core supports build-time OpenAPI document generation through the Microsoft.Extensions.ApiDescription.Server package.
Install it:
dotnet add package Microsoft.Extensions.ApiDescription.Server
Add the following configuration to the API project file:
<PropertyGroup>
<OpenApiGenerateDocumentsOnBuild>true</OpenApiGenerateDocumentsOnBuild>
<OpenApiDocumentsDirectory>
$(MSBuildProjectDirectory)/artifacts/openapi
</OpenApiDocumentsDirectory>
<OpenApiGenerateDocumentsOptions>
--file-name openapi
</OpenApiGenerateDocumentsOptions>
</PropertyGroup>
The OpenApiGenerateDocumentsOnBuild property enables document generation during the build.
The OpenApiDocumentsDirectory property specifies where the generated document should be stored.
The file-name option makes the generated document easier to reference in subsequent automation steps.
Build the application:
dotnet build
After a successful build, the OpenAPI document is available in the configured output directory.
artifacts/
openapi/
openapi.json
The generated file becomes an input for the client-generation process.
This approach has an important advantage: the API contract is generated from the application being built rather than downloaded from an independently deployed environment.
That makes the build process more predictable and reduces the possibility of generating a client from an outdated server.
Generating Strongly Typed API Clients
Once the OpenAPI document is available, a client generator can transform it into source code.
Several tools support this process:
NSwag can generate C# and TypeScript clients.
OpenAPI Generator supports multiple programming languages and client libraries.
Microsoft Kiota generates API clients from OpenAPI descriptions.
Visual Studio Connected Services provides an integrated client-generation experience.
The appropriate choice depends on the target language, serialization requirements, supported OpenAPI features, and project architecture.
For an ASP.NET Core application with a C# consumer, NSwag is a practical option.
Installing NSwag
NSwag supports command-line generation, MSBuild integration, and configuration files.
For a repeatable CI workflow, pin the tool version instead of allowing every developer or build agent to use a different version.
You can install NSwag as a local .NET tool:
dotnet new tool-manifest
dotnet tool install NSwag.ConsoleCore --version <pinned-version>
The tool manifest records the selected version in the repository.
Other developers and build agents can restore the same tool:
dotnet tool restore
Generating a C# client
Use the generated OpenAPI document as the input:
dotnet tool run nswag openapi2csclient \
/input:artifacts/openapi/openapi.json \
/output:src/Clients/Generated/CustomerApiClient.cs \
/classname:CustomerApiClient \
/namespace:MyApplication.Clients
The command generates a C# client based on the API contract.
The generated code typically includes:
API methods for supported endpoints.
Request and response models.
HTTP request handling.
Serialization and deserialization.
Query and route parameter handling.
Response status handling.
The exact output depends on the OpenAPI document and generator configuration.
A consumer can now use the generated client rather than manually constructing HTTP requests.
For example:
var httpClient = new HttpClient
{
BaseAddress = new Uri("https://localhost:5001")
};
var customerClient = new CustomerApiClient(httpClient);
var customer = await customerClient.GetCustomerAsync(10);
The generated method name depends on the operation ID and generator settings. Ensure the API operations have stable operation IDs if predictable client method names are important.
Why operation IDs matter
Consider these endpoints:
app.MapGet("/api/customers/{id:int}",
GetCustomer);
app.MapPost("/api/customers",
CreateCustomer);
If the OpenAPI document does not contain meaningful operation IDs, a generator may produce method names based on paths, HTTP methods, or its own naming conventions.
This can create inconsistent method names when endpoints change.
You can explicitly define operation IDs:
app.MapGet("/api/customers/{id:int}",
GetCustomer)
.WithName("GetCustomer");
app.MapPost("/api/customers",
CreateCustomer)
.WithName("CreateCustomer");
Stable operation IDs make generated clients easier to read and reduce unnecessary changes when the API evolves.
Treat operation IDs as part of the public contract rather than incidental implementation details.
Keeping Generated Code Separate From Handwritten Code
One common mistake is editing generated client files directly.
For example, a developer might add a custom method, modify a generated property, or change an HTTP request implementation to handle a special business requirement.
The next time the client is generated, those modifications may disappear.
Generated code should be treated as an output of the generation process, not as the primary location for application logic.
A cleaner project structure separates generated code from handwritten code:
src/
Api/
Controllers/
Models/
Program.cs
Clients/
Generated/
CustomerApiClient.cs
Services/
CustomerService.cs
Extensions/
CustomerClientExtensions.cs
The generated client contains code produced by NSwag.
The handwritten service layer contains application-specific behavior:
public sealed class CustomerService
{
private readonly CustomerApiClient _client;
public CustomerService(CustomerApiClient client)
{
_client = client;
}
public async Task<CustomerDto?> GetCustomerAsync(
int customerId,
CancellationToken cancellationToken)
{
var response = await _client.GetCustomerAsync(customerId);
if (response is null)
{
return null;
}
return new CustomerDto
{
Id = response.Id,
Name = response.Name,
Email = response.Email
};
}
}
The example illustrates the separation between generated transport code and application-specific behavior. In a real implementation, cancellation tokens and other options should be passed through the generated method when supported by the selected generator configuration.
This separation provides several benefits:
Generated code can be replaced safely.
Business rules remain independent of code generation.
Client-specific behavior can be tested separately.
Changes to generator templates do not require rewriting application logic.
Multiple clients can use the same generated contract.
If customization is required, use generator configuration, templates, partial classes, extension methods, or wrapper services rather than modifying generated files directly.
Detecting Outdated Generated Clients
Generating the client is only one part of the solution.
The next step is ensuring that the generated output is always synchronized with the current OpenAPI document.
A reliable approach is to regenerate the client during CI and compare the result with the version committed to source control.
Consider the following workflow:
Restore dependencies.
Build the ASP.NET Core API.
Generate the OpenAPI document.
Generate the API client.
Compare generated files with the committed versions.
Fail the build if unexpected differences exist.
This approach makes API contract changes visible during pull requests.
Comparing generated code locally
After generating the client, run:
git diff -- src/Clients/Generated
If the output contains changes, the generated client differs from the version committed to the repository.
This does not automatically mean that the change is incorrect. It means the contract or generation output has changed and needs review.
After reviewing the differences, regenerate and commit the client:
git add src/Clients/Generated
git commit -m "Update generated API client"
Failing CI when generated code is outdated
A CI pipeline can use the following command:
git diff --exit-code -- src/Clients/Generated
The command returns a non-zero exit code when the generated files differ from the committed versions.
That makes the pipeline fail and prevents an outdated generated client from passing unnoticed.
This check is especially useful when backend and frontend code are maintained in the same repository.
Automating Client Generation With GitHub Actions
A CI workflow can automate the entire process whenever a pull request changes the API.
The following example uses GitHub Actions, .NET, build-time OpenAPI generation, and NSwag.
Assume the repository contains:
MySolution/
src/
Api/
Api.csproj
Clients/
Generated/
.config/
dotnet-tools.json
The API project generates its OpenAPI document during the build.
The repository also contains a local NSwag tool manifest with a pinned version.
Create the workflow file:
.github/workflows/validate-api-client.yml
Add the following configuration:
name: Validate Generated API Client
on:
pull_request:
paths:
- 'src/Api/**'
- 'src/Clients/Generated/**'
- '.config/dotnet-tools.json'
- '.github/workflows/validate-api-client.yml'
push:
branches:
- main
jobs:
validate-client:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Set up .NET
uses: actions/setup-dotnet@v4
with:
dotnet-version: '<supported-sdk-version>'
- name: Restore dependencies
run: dotnet restore
- name: Restore local tools
run: dotnet tool restore
- name: Build API and generate OpenAPI
run: dotnet build src/Api/Api.csproj --no-restore
- name: Generate API client
run: |
dotnet tool run nswag openapi2csclient \
/input:src/Api/artifacts/openapi/openapi.json \
/output:src/Clients/Generated/CustomerApiClient.cs \
/classname:CustomerApiClient \
/namespace:MyApplication.Clients
- name: Check generated client changes
run: git diff --exit-code -- src/Clients/Generated
Replace the SDK placeholder with the SDK supported by the application, and adjust the paths and generator options to match the repository.
The workflow performs the following operations:
Checks out the repository.
Installs the required .NET SDK.
Restores project dependencies.
Restores the pinned NSwag tool.
Builds the API and generates the OpenAPI document.
Generates the C# client from that document.
Checks whether the generated client differs from the committed version.
If the backend contract changes but the generated client is not updated, the final step fails.
The developer can then regenerate the client locally, review the changes, and include them in the pull request.
For production workflows, also pin GitHub Actions to reviewed commit SHAs according to the organization's dependency-management policy. The version tags above make the example easier to read but are not immutable references.
Understanding Breaking and Non-Breaking API Changes
Not every API contract change has the same impact.
A new optional response property is generally easier for existing clients to tolerate than a removed property or a newly required request field.
It is important to distinguish between breaking and non-breaking changes before updating generated clients.
Non-breaking changes
Examples of changes that are commonly compatible with existing consumers include:
Adding an optional response property.
Adding a new endpoint without changing existing endpoints.
Adding a new optional query parameter.
Adding documentation descriptions or examples.
Adding a new response header that existing consumers can ignore.
However, compatibility depends on the client implementation, serialization settings, and how consumers process responses.
For example, an older client may ignore an additional JSON property, but a strict deserializer or custom validation layer may behave differently.
Breaking changes
The following changes can break existing clients:
Removing an endpoint.
Renaming an existing property.
Changing a property from optional to required.
Changing a property data type.
Changing an HTTP method.
Changing a response structure.
Removing a supported response status.
Adding a required request parameter.
Changing enum values when consumers use strict enum handling.
Consider this request model:
public sealed class CreateCustomerRequest
{
public string Name { get; set; } = string.Empty;
public string Email { get; set; } = string.Empty;
}
Suppose the API changes it to:
public sealed class CreateCustomerRequest
{
public string Name { get; set; } = string.Empty;
public string Email { get; set; } = string.Empty;
public string PhoneNumber { get; set; } = string.Empty;
}
The addition of PhoneNumber is not automatically a breaking change.
If the server accepts requests without that property, existing clients may continue to work.
However, if the server starts requiring a valid phone number, older clients may receive validation errors.
The important distinction is the actual contract behavior, not simply whether a property was added.
Use API compatibility checks
A generated client comparison detects changes in generated source code, but it does not explain whether a change is backward-compatible.
For larger systems, consider adding an OpenAPI compatibility checker to the pipeline.
Such a tool can compare the previous API specification with the new one and identify potentially breaking changes.
A useful process is:
Store the released OpenAPI document as a baseline.
Generate the current document from the API project.
Compare the two documents.
Identify removed operations, changed schemas, and incompatible parameter changes.
Require review when a breaking change is detected.
This is especially useful when several independently deployed applications consume the same API.
Handling Nullable and Required Properties Correctly
Nullable and required properties are a frequent source of unexpected client-generation problems.
Consider the following model:
public sealed class CustomerResponse
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public string? MiddleName { get; set; }
}
The application allows MiddleName to be null.
The generated OpenAPI schema should describe that behavior accurately.
A client generator uses the schema to determine how the corresponding property should be represented.
For example, a C# client might generate:
public int Id { get; set; }
public string Name { get; set; }
public string? MiddleName { get; set; }
If the OpenAPI document incorrectly marks a nullable property as required, generated clients may enforce stricter assumptions than the server actually requires.
The reverse problem is also possible. If a property must always be present but the OpenAPI schema describes it as optional, client developers may incorrectly assume that it can be omitted.
To reduce these problems:
Enable nullable reference types in the API project.
Use validation attributes or endpoint validation consistently.
Verify required and nullable schema information.
Inspect the generated OpenAPI document when model behavior changes.
Test generated clients against actual API responses.
Nullable reference types are a compiler feature. They do not automatically guarantee that every runtime validation rule is reflected correctly in the OpenAPI document.
The generated contract must be reviewed to ensure that it describes the API's actual behavior.
Managing Enums and Polymorphic Models
Enums and polymorphic models require special attention during client generation.
Consider an order status:
public enum OrderStatus
{
Pending,
Processing,
Completed,
Cancelled
}
The server might serialize enum values as strings or numbers depending on its JSON configuration.
For example, a string-based representation could look like:
{
"id": 101,
"status": "Processing"
}
A numeric representation might look like:
{
"id": 101,
"status": 1
}
The OpenAPI schema and generated client must agree on the representation.
If the server uses string-based enum serialization, make sure the generated document describes string enum values correctly.
Polymorphic models also need explicit contract information.
For example, an API may return different payment types:
public abstract class PaymentResponse
{
public decimal Amount { get; set; }
}
public sealed class CardPaymentResponse : PaymentResponse
{
public string LastFourDigits { get; set; } = string.Empty;
}
public sealed class UpiPaymentResponse : PaymentResponse
{
public string UpiId { get; set; } = string.Empty;
}
A generated client needs to know how to distinguish the different response types.
OpenAPI supports schema composition and discriminator information, but the API's serialization behavior and generated schema must be configured consistently.
Do not assume that defining an inheritance hierarchy in C# automatically produces a client that handles every polymorphic scenario correctly.
Test representative JSON payloads using the actual generated client.
Handling API Versioning
API versioning is another important part of keeping generated clients synchronized.
Consider an application that exposes:
/api/v1/customers
/api/v2/customers
The first version may return a basic customer response, while the second version includes additional information.
If both versions are consumed by different applications, generating a single client from an ambiguous or combined document can create confusion.
A better approach is to generate separate OpenAPI documents:
openapi-v1.json
openapi-v2.json
Then generate corresponding clients:
CustomerApiClientV1.cs
CustomerApiClientV2.cs
Each client represents a specific API contract.
This approach provides several advantages:
Existing applications can continue using their supported API version.
New applications can adopt newer endpoints.
Changes can be reviewed independently.
Client generation can be automated separately for each version.
Breaking changes can be introduced through a new contract rather than silently changing an existing one.
API versioning should be designed around consumer compatibility and release requirements.
Simply adding a version number to a URL does not guarantee backward compatibility. The contract and implementation must remain consistent.
Testing Generated Clients Against the API
A generated client that compiles successfully is not necessarily a correct client.
Compilation verifies that the generated source code is valid according to the compiler. It does not prove that the client communicates correctly with the deployed API.
For example, a client may compile while sending an incorrect query parameter or using a different enum representation than the server expects.
A stronger validation process includes several levels of testing.
Build-time validation
Generate the client and compile the consumer project.
dotnet build
This catches problems such as:
Missing generated types.
Renamed client methods.
Incompatible method signatures.
Invalid generated source code.
Changes that break handwritten code using the client.
Contract tests
Contract tests validate that the API behaves according to the documented contract.
For example, a test can verify that a customer endpoint returns the expected response structure.
[Fact]
public async Task GetCustomer_ReturnsExpectedResponse()
{
var response = await _client.GetAsync("/api/customers/10");
response.EnsureSuccessStatusCode();
var customer = await response.Content
.ReadFromJsonAsync<CustomerResponse>();
Assert.NotNull(customer);
Assert.Equal(10, customer.Id);
Assert.False(string.IsNullOrWhiteSpace(customer.Name));
}
This example uses a test HTTP client configured for the API application.
For more complete contract validation, verify required properties, nullable fields, status codes, headers, and representative error responses.
Integration tests using the generated client
Another useful test is to use the generated client itself against an API test host.
The test can verify that the generated methods correctly serialize requests and deserialize responses.
This helps identify issues that ordinary controller tests might not catch.
For example:
A date value is serialized in an unexpected format.
An enum is represented differently than expected.
A nullable response property causes deserialization problems.
A generated method does not handle a particular HTTP status.
A request body does not match the server's validation requirements.
Combining contract tests with generated-client integration tests provides stronger confidence than relying only on compilation.
Common Mistakes to Avoid
Keeping generated clients synchronized requires more than adding a generation command to a pipeline.
Several implementation mistakes can make the process unreliable.
Generating clients from a deployed development API
A common approach is to download the OpenAPI document from a shared development environment and generate the client from it.
This can create inconsistencies when the environment contains a different build from the code being reviewed.
For example, a developer may change an endpoint locally while the development server still exposes the previous implementation.
The generated client then reflects the deployed environment rather than the source code in the pull request.
Prefer generating the OpenAPI document from the application being built whenever possible.
Allowing developers to use different generator versions
Different NSwag versions or generator configurations may produce different code from the same OpenAPI document.
That can lead to large, unnecessary source-control changes.
Use a local tool manifest or another dependency-management mechanism to pin the generator version.
Keep the configuration in source control and update it deliberately.
Editing generated files manually
Manual changes inside generated files are likely to disappear during regeneration.
Move custom behavior into wrapper services, extension methods, partial classes, or supported generator customization points.
Ignoring OpenAPI schema changes
A successful client-generation command does not guarantee that the generated client is correct.
Inspect important schema changes, especially when modifying:
Treating generated-code differences as automatic breaking changes
Generated source-code changes can occur because of formatting, naming, generator versions, or schema descriptions.
Not every difference represents a compatibility problem.
Review the OpenAPI contract and classify the change before deciding whether it is safe.
Exposing internal OpenAPI documents unintentionally
An OpenAPI document can reveal endpoint names, request structures, internal operations, and other implementation details.
The document endpoint should be protected according to the API's security requirements.
For example, exposing it only in development is a reasonable default for many applications:
if (app.Environment.IsDevelopment())
{
app.MapOpenApi();
}
If a production document is needed for an internal integration or client-generation process, use an appropriate authentication and authorization strategy or publish the document as a protected build artifact.
The OpenAPI document is not an authorization mechanism. API endpoints must still enforce their own security policies.
Recommended Architecture for Reliable Client Generation
For applications with multiple API consumers, a consistent contract-generation architecture helps reduce maintenance effort.
A practical workflow looks like this:
ASP.NET Core API
|
v
Build Application
|
v
Generate OpenAPI Document
|
v
Validate OpenAPI Contract
|
v
Generate API Clients
|
v
Compile Consumer Projects
|
v
Run Contract and Integration Tests
|
v
Compare Generated Code
|
v
Review and Merge Changes
Each stage has a specific responsibility.
The ASP.NET Core application is the source of the API implementation.
The OpenAPI document describes the API contract.
The client generator converts the contract into strongly typed code.
The compiler verifies that consumer projects remain compatible with the generated source.
Contract and integration tests validate actual request and response behavior.
Finally, the source-control comparison ensures that generated files are not outdated.
For a small application, this process can run in a single CI job.
For a larger system, it can be separated into independent jobs for API generation, client generation, compatibility checking, and consumer testing.
Production Best Practices
The following practices make generated API clients easier to maintain across teams and environments.
Treat the OpenAPI document as a versioned API contract.
Generate the document from the same application source being validated.
Pin the client generator version.
Keep generator configuration in source control.
Use stable operation IDs.
Separate generated code from handwritten application logic.
Avoid manually editing generated source files.
Generate different clients for different API versions when required.
Review nullable, required, enum, and polymorphic schema changes carefully.
Fail CI when committed generated code is outdated.
Add compatibility checks before releasing breaking contract changes.
Compile consumer projects after regenerating clients.
Test generated clients against real API behavior.
Protect internal OpenAPI documents from unintended public exposure.
Publish OpenAPI documents as build artifacts when other teams need to consume them.
One additional consideration is reproducibility.
The same source code, OpenAPI configuration, generator version, and generator settings should produce consistent output. If generated code changes unexpectedly between machines, investigate differences in tool versions, runtime environments, configuration, and input documents.
This reduces noisy pull requests and makes genuine API contract changes easier to identify.
Conclusion
Generated API clients make communication between ASP.NET Core applications and their consumers more predictable. They reduce repetitive HTTP code, provide strongly typed request and response models, and help developers detect incompatible changes earlier.
However, client generation should not be treated as a one-time development task.
The API contract changes as an application evolves. If generated clients are not updated alongside those changes, the server and consumer applications can gradually become inconsistent.
A reliable approach is to generate OpenAPI documents during the application build, generate clients using a pinned tool version, and validate the generated output through CI.
Combining source-control comparisons, API compatibility checks, compilation, and integration tests creates a repeatable process that helps teams identify contract changes before they reach production.
The most important principle is simple: whenever the API contract changes, the generated clients and their tests should be validated as part of the same development workflow.
Join the conversation! Your thoughts help the community grow.