An API can compile successfully, pass its unit tests, and still break applications that depend on it. This often happens when a developer changes a request model, removes an endpoint, modifies a response type, or changes an authentication requirement without realizing that another application relies on the existing behavior.
These problems become more difficult to manage when multiple teams consume the same API. A change that looks small inside an ASP.NET Core project can affect mobile applications, web clients, partner integrations, and other services. Developers may discover the problem only after deployment, when an existing client starts receiving unexpected responses or its generated SDK no longer works.
One practical way to prevent these problems is to compare OpenAPI specifications automatically during code review. Instead of depending only on developers to identify risky changes, a CI pipeline can generate the API specification, compare it with the previously approved version, and report changes that could break existing clients.
This article explains how to implement this approach in an ASP.NET Core application using built-in OpenAPI support and oasdiff.
Why Normal Build and Unit Tests Are Not Enough
A successful build confirms that the application code is valid from the compiler's perspective. Unit tests confirm that selected parts of the application behave as expected. Neither automatically confirms that the public HTTP contract remains compatible with existing consumers.
Consider an API 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;
}
A mobile application may use the Email property to display customer details. Another service may depend on the same property when creating an invoice.
Now imagine that a developer renames Email to EmailAddress:
public sealed class CustomerResponse
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public string EmailAddress { get; set; } = string.Empty;
}
The ASP.NET Core project can still compile. Its unit tests may also pass if they test only the service implementation and do not verify the response contract. However, clients expecting the email property may no longer receive the data they need.
Other changes can cause similar problems:
Removing an endpoint or changing its HTTP method.
Making an optional query parameter required.
Changing a request property from a string to an integer.
Removing a response property that clients depend on.
Adding a new required property to an existing request.
Removing a previously supported response status code.
Changing the authentication requirements of an endpoint.
These are API compatibility concerns rather than ordinary compilation errors. To detect them reliably, the CI pipeline needs to understand the API's published contract.
Use OpenAPI as the API Contract
OpenAPI provides a machine-readable description of an HTTP API. It describes endpoints, HTTP methods, parameters, request bodies, response schemas, status codes, and security requirements.
ASP.NET Core can generate this document from endpoint definitions and associated metadata. A comparison tool can then inspect two specifications and identify changes that may affect existing clients.
For example, suppose the released API has this endpoint:
GET /api/customers/{id}
It returns a customer response containing id, name, and email.
A developer modifies the API and publishes a new specification. A comparison tool can examine the old and new documents and report whether the endpoint disappeared, its parameters changed, or its response schema became incompatible.
This approach is useful because the comparison focuses on the HTTP contract rather than the internal implementation. Developers can refactor services, change repositories, or reorganize controllers without generating compatibility warnings when the published API remains unchanged.
Generate OpenAPI Documents in ASP.NET Core
ASP.NET Core provides built-in OpenAPI document generation through the Microsoft.AspNetCore.OpenApi package. The AddOpenApi method registers document generation, while MapOpenApi exposes the generated document through an HTTP endpoint.
Install the package in your API project:
dotnet add package Microsoft.AspNetCore.OpenApi
For a controller-based API, configure OpenAPI alongside the controller services:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddOpenApi();
var app = builder.Build();
app.MapControllers();
if (app.Environment.IsDevelopment())
{
app.MapOpenApi();
}
app.Run();
The OpenAPI document is available at:
/openapi/v1.json
The document name defaults to v1. You can also register multiple documents when an application exposes different API versions or separates public and internal endpoints.
For example:
builder.Services.AddOpenApi("v1");
builder.Services.AddOpenApi("v2");
You can then expose the documents using:
app.MapOpenApi();
The generated document can describe different API groups, depending on how endpoint metadata and document inclusion are configured. This is particularly useful when a single application maintains multiple API versions.
OpenAPI generation is not the same as providing an interactive Swagger UI. The built-in package generates the specification; a separate user interface can be added if developers need an interactive documentation experience.
For automated compatibility checks, the important requirement is a reliable way to generate the same API document on every build.
Generate the OpenAPI Document During the Build
Starting with .NET 9, ASP.NET Core includes built-in OpenAPI support. You can also generate documents during the build instead of starting the application and requesting the OpenAPI endpoint.
Install the build-time generation package:
dotnet add package Microsoft.Extensions.ApiDescription.Server
After installation, run:
dotnet build
The package generates the configured OpenAPI documents during the build and places them in the application's output area. The generated document can then be used by another tool or CI step.
For example, the following command displays a generated document on Linux or macOS:
cat obj/YourApiProject.json
Replace YourApiProject.json with the actual generated file name for your project. The exact output location can be customized through the OpenApiDocumentsDirectory project property.
You can configure the output directory in the project file:
<PropertyGroup>
<OpenApiDocumentsDirectory>.</OpenApiDocumentsDirectory>
</PropertyGroup>
This places the generated document alongside the project file. Keeping the output in a predictable location makes it easier for CI scripts to locate and compare the specification.
Build-time generation also invokes the application's entry point using a mock server implementation. Startup code that reads configuration or registers external services may therefore run during document generation. If your application requires unavailable infrastructure during startup, review that initialization logic and separate document-generation requirements from operations that need live services.
Identify Breaking Changes With oasdiff
Generating two OpenAPI documents is only part of the process. The next step is comparing them.
oasdiff is an OpenAPI comparison tool that identifies changes between API specifications. It can report all changes or focus specifically on changes that may break existing clients.
For example, imagine that the released API specification is stored as openapi-baseline.yaml, while the new specification is generated as openapi-current.yaml.
You can compare them using the command-line tool:
oasdiff breaking openapi-baseline.yaml openapi-current.yaml
The command reports changes classified as breaking. This makes it suitable for a CI check that runs before a pull request is merged.
A few examples of changes that should receive attention include:
API change | Compatibility concern |
|---|
Removing an existing endpoint | Existing clients may receive a 404 response |
Adding a required request property | Older clients may send requests that no longer satisfy the contract |
Changing a request property type | Existing request payloads may become invalid |
Removing a response property | Clients may no longer receive data they depend on |
Adding a new required query parameter | Existing requests may be rejected |
Removing a supported response status code | Clients may lose a response they explicitly handle |
Not every change is breaking. Adding an optional request property generally allows existing clients to continue sending their original requests. Adding an optional response property is also commonly treated as compatible by schema-based comparison tools, although clients with strict deserialization rules should still be tested.
The important distinction is how the change affects existing requests and responses. A new required request field narrows what the server accepts. A response change that allows values outside the previous contract can introduce values that existing clients were not designed to handle.
A tool such as oasdiff applies compatibility rules to these changes rather than treating every difference as equally important.
Automate the Check With GitHub Actions
Once the application can generate an OpenAPI document and the repository has a baseline specification, the comparison can run automatically on every pull request.
The baseline should represent a released or otherwise approved API contract. It should not be replaced with the latest generated document before the comparison, because that would remove the reference needed to identify changes.
A simple repository structure could look like this:
MyApi/
│
├── Controllers/
├── Models/
├── Program.cs
├── MyApi.csproj
├── openapi.yaml
└── .github/
└── workflows/
└── api-compatibility.yml
Here, openapi.yaml is the approved baseline. The CI pipeline generates a new specification from the pull request and compares it with the baseline.
The following workflow demonstrates the comparison step using the official oasdiff GitHub Action:
name: API Compatibility Check
on:
pull_request:
branches:
- main
permissions:
contents: read
pull-requests: write
jobs:
breaking-changes:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v7
- name: Fetch base branch
run: git fetch --depth=1 origin ${{ github.base_ref }}
- name: Compare API specifications
uses: oasdiff/oasdiff-action/breaking@v0
with:
base: 'origin/${{ github.base_ref }}:openapi.yaml'
revision: 'HEAD:openapi.yaml'
fail-on: ERR
This workflow assumes that the pull request has already generated or updated openapi.yaml before the comparison step. In a complete pipeline, add the .NET SDK setup, restore, build-time OpenAPI generation, and a copy step that places the newly generated document at that path.
The base input identifies the specification from the target branch, while revision identifies the specification in the pull request. The fail-on setting controls which severity level should fail the job. In this example, the pipeline blocks changes classified as errors.
The action can also add annotations and a pull request report so reviewers can inspect the detected changes. If the team does not want the comparison uploaded for side-by-side review, the action provides a review: false option.
For a real project, pin third-party GitHub Actions to reviewed versions or commit SHAs according to your organization's supply-chain policy. Also ensure the workflow has the permissions it needs and no broader permissions than necessary.
Decide Which Changes Should Block a Pull Request
A compatibility tool can identify potentially risky changes, but the development team still needs a clear policy for handling them.
A useful starting point is to block confirmed breaking changes by default. If a developer intentionally removes an endpoint or changes a request schema, the pull request should explain why the change is necessary and how existing clients will be migrated.
Warnings and informational changes can follow a different review process. For example, removing an optional request parameter may deserve attention because some clients could still send it, even when the new server implementation ignores it. A warning does not always mean that every client will fail, but it should not be dismissed without understanding the impact.
oasdiff supports configuration through a .oasdiff.yaml file. Teams can use this configuration to define severity thresholds and exclusions that match their compatibility policy. Keep these settings in source control so that developers and CI use the same rules.
It is also useful to establish a deprecation process. Instead of removing an endpoint immediately, mark it as deprecated, communicate the replacement, and provide a realistic migration period. Once consumers have moved to the new endpoint, the old one can be removed through an approved change.
This approach makes compatibility decisions visible during code review rather than leaving them to production support teams.
Keep OpenAPI Specifications Accurate
Automated comparison is only as reliable as the specification being compared. If an API document does not describe the actual HTTP behavior, the tool cannot detect changes that are missing from that document.
For example, an endpoint may return different response shapes depending on application configuration, user permissions, or runtime conditions. If those differences are not represented in OpenAPI metadata, a specification comparison cannot identify them.
Developers should document response types and status codes explicitly, particularly for controller actions with multiple possible outcomes. For example:
[ApiController]
[Route("api/customers")]
public sealed class CustomersController : ControllerBase
{
[HttpGet("{id:int}")]
[ProducesResponseType<CustomerResponse>(
StatusCodes.Status200OK)]
[ProducesResponseType(
StatusCodes.Status404NotFound)]
public IActionResult GetCustomer(int id)
{
var customer = FindCustomer(id);
if (customer is null)
{
return NotFound();
}
return Ok(customer);
}
private static CustomerResponse? FindCustomer(int id)
{
return id == 1
? new CustomerResponse
{
Id = 1,
Name = "John",
Email = "[email protected]"
}
: null;
}
}
The response metadata helps the generated document describe the endpoint's expected outcomes. The example uses a simplified lookup method; a production application would normally use an injected service or repository.
Teams should also review custom OpenAPI transformers, schema filters, and environment-specific document generation. These can change the final specification even when the controller code remains unchanged.
For APIs that support multiple versions, generate and compare each published version independently. A change to a new API version should not accidentally replace the baseline for an older version that existing clients still use.
Understand What OpenAPI Comparison Cannot Detect
OpenAPI comparison is a valuable compatibility check, but it does not prove that the API behaves correctly at runtime.
A specification can remain unchanged while business logic changes significantly. For example, an endpoint may continue accepting the same request and returning the same response schema but start calculating a different price or applying a different authorization rule. A document comparison cannot determine whether that behavior is correct.
It also cannot automatically discover every undocumented runtime condition. If the application returns a response that is not described in its OpenAPI document, the comparison tool has no reliable contract information to evaluate.
For this reason, combine specification comparison with other testing approaches:
Unit tests should verify business rules and individual application components.
Integration tests should exercise real HTTP requests and responses.
Contract tests should verify important interactions between specific consumers and providers.
OpenAPI comparison should identify incompatible changes to the published API definition.
These checks cover different risks. They work best together rather than replacing one another.
Conclusion
API breaking changes often enter production because developers review implementation code without comparing the public contract against the version existing clients already use.
ASP.NET Core's OpenAPI support makes it possible to generate API specifications during development or as part of the build. Tools such as oasdiff can compare those specifications and identify changes that may affect existing consumers. By adding this comparison to GitHub Actions or another CI system, teams can detect compatibility problems while reviewing a pull request.
The most important part is maintaining an accurate baseline and treating compatibility reports as part of the development process. When breaking changes are intentional, developers can plan deprecation, migration, and versioning instead of surprising existing clients after deployment.
Join the conversation! Your thoughts help the community grow.