A contract-first workflow between ASP.NET Core and a TypeScript frontend: build-time OpenAPI generation in .NET 10, choosing a TypeScript generator (openapi-typescript, Orval, NSwag, Kiota), committing and diffing the spec, breaking-change detection in CI, and evolution rules for DTOs.
Make the OpenAPI document the contract and generate everything from it. In .NET 10, AddOpenApi() produces an OpenAPI 3.1 document, and Microsoft.Extensions.ApiDescription.Server writes it to a file at build time. Commit that file so every API change shows up as a diff in the pull request.
The frontend generates its TypeScript types or client from the file (openapi-typescript, Orval, NSwag or Kiota), so a renamed property fails tsc instead of failing in production. CI runs a breaking-change diff (for example oasdiff) against main and blocks removals, renames and new required inputs unless the API version changes.
The trade-off: a little pipeline work and discipline about schema accuracy, in exchange for turning runtime contract bugs into compile-time and PR-time failures.
"The root problem is that the contract lives in two places: C# records and hand-written TypeScript types, and nothing checks they agree. I fix that by making the OpenAPI document the single source and generating the TypeScript from it. In .NET 10, the built-in
Microsoft.AspNetCore.OpenApipackage generates OpenAPI 3.1, and if I addMicrosoft.Extensions.ApiDescription.Server, the document is written to disk on every build. I commit that JSON file. Now a pull request that renamescustomerNametocustomershows a one-line change inopenapi.jsonthat reviewers can't miss.On the frontend, a script generates types from that file. I like
openapi-typescriptwithopenapi-fetchbecause it's types only, so there's almost no runtime code, but Orval is great if you want TanStack Query hooks generated, and NSwag or Kiota if you want full clients. The generated code is never edited by hand. Then CI does two things: it runs the TypeScript typecheck against the freshly generated types, so the UI breaks at build time, and it runs a breaking-change diff like oasdiff between the branch's spec and main's. For example, on [project] adding that check blocked [N] breaking changes in the first [quarter] that would previously have reached production, including a nullable field that became required.The mistake I see is generating from an inaccurate document. If endpoints return
IResultwithout metadata, or nullable reference types are off, the spec says everything is optional or unknown and the generated types are useless. So I useTypedResults, enable nullable, and mark required members. My rule for evolution is simple: additive is free; removing, renaming, changing a type or tightening validation needs a deprecation period or a new version."
| Stage | Tool | Fails when |
|---|---|---|
| API build | ApiDescription.Server writes openapi.json |
Never; just produces the file |
| PR review | Git diff of openapi.json |
A human spots an unexpected change |
| Breaking check | oasdiff (or similar) vs main |
Removed path/field, new required input, type change |
| Frontend build | Generator + tsc --noEmit |
UI uses a field that no longer exists |
| Contract tests (optional) | Integration test comparing live doc with committed file | Someone forgot to commit the regenerated spec |
| Generator | Output | When it fits |
|---|---|---|
| openapi-typescript (+ openapi-fetch) | Types only, tiny runtime | You want control and small bundles |
| Orval | Types + fetch/axios + TanStack Query hooks | React teams using TanStack Query |
| NSwag | Full TypeScript or C# clients | Existing NSwag users, Angular services |
| Kiota | Fluent clients in many languages | Many client languages, Microsoft Graph style |
| Change | Safe? |
|---|---|
| Add optional request field / new response field | Yes |
| Add a new endpoint | Yes |
| Remove or rename a response field | No: deprecate first |
| Make an optional request field required | No |
| Widen an enum in a response | Risky: clients must handle unknown values |
After introducing a committed spec, generated types and an oasdiff gate on [a 40-endpoint API], contract-related production incidents dropped from about [2 a month] to [none in six months], and the CI step added under 20 seconds per build.
Checks whether the candidate can stop frontend/backend contract drift with a practical pipeline rather than relying on communication.
Green flags
Red flags
Endpoints + metadata (TypedResults, Produces, [Required], nullable)
│ ApiExplorer
▼
Microsoft.AspNetCore.OpenApi ──► OpenAPI 3.1 document (runtime: /openapi/v1.json)
│ Microsoft.Extensions.ApiDescription.Server (build)
▼
openapi.json committed ──► frontend generator ──► api-types.ts ──► tsc
The generator reads ApiExplorer metadata. TypedResults.Ok<OrderDto>() and Results<Ok<OrderDto>, NotFound> give it response types automatically; a bare IResult does not. Nullable reference types decide whether properties are nullable; C# required members and [Required] mark required properties.
.NET 10 emits OpenAPI 3.1 by default, which aligns with JSON Schema 2020-12. Nullable is expressed as type: ["string", "null"] instead of 3.0's nullable: true. Make sure your generator supports 3.1, or configure the document version to 3.0 for older tools.
Adding Microsoft.Extensions.ApiDescription.Server hooks an MSBuild target that starts the app's host in a special mode after build and writes the document to obj/ or a folder you choose with OpenApiDocumentsDirectory. Startup code that connects to databases or Key Vault must tolerate this, so guard it (for example check Assembly.GetEntryAssembly()?.GetName().Name == "GetDocument.Insider") or keep side effects out of start-up.
A diff tool compares two specs structurally: removed paths, removed response properties, request properties that became required, type changes, narrowed enums. It understands direction: removing a response field breaks clients; removing an optional request field usually does not. Run it in CI with the base branch's committed spec as the baseline.
In a monorepo, one PR changes C#, the spec and the TypeScript together, and the frontend typecheck runs on the same commit. With separate repos, publish the spec (or a generated npm package) as a versioned artefact from the API pipeline and let the frontend upgrade deliberately; the breaking-change gate becomes even more important.
OpenAPI describes shape, not behaviour. It will not tell you a field now means something different, or that an endpoint's sort order changed. Complement it with consumer-driven contract tests (Pact) for critical integrations and with ProblemDetails conventions for errors.
AddOpenApi() and MapOpenApi() to a Minimal API and open /openapi/v1.json.Microsoft.Extensions.ApiDescription.Server, build, and find the generated file.npx openapi-typescript openapi.json -o src/api-types.ts and use the types with openapi-fetch.tsc fail in the React code.oasdiff breaking between the old and new spec and read the report.The API side producing an accurate spec at build time, the frontend generation, and the CI gate.
<!-- Api.csproj -->
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<!-- Nullable annotations decide which schema properties are nullable: without this, generated types lie. -->
<Nullable>enable</Nullable>
<!-- Where the build writes the document; a committed folder gives reviewers and oasdiff a baseline. -->
<OpenApiDocumentsDirectory>$(MSBuildProjectDirectory)/../contracts</OpenApiDocumentsDirectory>
</PropertyGroup>
<ItemGroup>
<!-- Runtime document generation (OpenAPI 3.1 by default in .NET 10). -->
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.*" />
<!-- Build-time generation: runs the app's host after build and writes the document to disk. -->
<PackageReference Include="Microsoft.Extensions.ApiDescription.Server" Version="10.*" PrivateAssets="all" />
</ItemGroup>
</Project>
// Program.cs (.NET 10)
using Microsoft.AspNetCore.Http.HttpResults;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddOpenApi(); // OpenAPI 3.1 by default
var app = builder.Build();
// The live endpoint maps your attack surface: only in Development (the committed file is the contract).
if (app.Environment.IsDevelopment())
app.MapOpenApi();
// TypedResults give the generator exact response types and status codes.
app.MapGet("/api/orders/{id:int}", Results<Ok<OrderDto>, NotFound> (int id) =>
id == 1 ? TypedResults.Ok(new OrderDto(1, "ACME Pty Ltd", null)) : TypedResults.NotFound());
app.Run();
// Nullable annotations become nullable schema types; 'Notes' is string | null in TypeScript.
public sealed record OrderDto(int Id, string Customer, string? Notes);
// web/package.json scripts: "gen:api": "openapi-typescript ../contracts/Api.json -o src/api-types.ts"
// web/src/api.ts — types only, generated; the client checks paths, params and bodies at compile time.
import createClient from "openapi-fetch";
import type { paths } from "./api-types";
export const api = createClient<paths>({ baseUrl: "/" });
export async function loadOrder(id: number) {
const { data, error } = await api.GET("/api/orders/{id}", { params: { path: { id } } });
if (error || !data) return null;
return data; // typed as { id: number; customer: string; notes: string | null }
}
# CI (GitHub Actions or Azure Pipelines step), triggered on changes to src/Api or web/
dotnet build src/Api -c Release # writes contracts/Api.json
git diff --exit-code contracts/ # fail if the committed spec is stale
oasdiff breaking origin/main:contracts/Api.json contracts/Api.json --fail-on ERR
cd web && npm ci && npm run gen:api && npx tsc --noEmit # UI must compile against the new contract
IResult without metadata. Why it is wrong: The spec has no response schema, so generated types are unknown. Instead: Use TypedResults and Results<...> or .Produces<T>().required members.This is less about tools than about where contract failures surface. Without a pipeline they surface in production, reported by users. With a committed spec they surface in code review; with a breaking-change gate they surface in CI; with generated types they surface in the developer's editor. Each step moves the failure earlier and makes it cheaper.
Keep it proportionate: for a monorepo with one SPA, generated types plus a frontend typecheck catches most problems. Add the breaking-change gate when the API has other consumers (mobile apps, partners, other microservices) who cannot upgrade in the same PR. With many consumers, the strategy shifts to evolution management: one OpenAPI document per major version (AddOpenApi("v1"), AddOpenApi("v2")), Asp.Versioning for URL or header versions, deprecation flags plus Deprecation and Sunset headers, and telemetry on which clients still call deprecated fields so you remove them on evidence. Add consumer-driven contract tests (Pact) only where behaviour, not shape, is the risk.
Security note: the runtime OpenAPI endpoint maps your whole attack surface. Serve it only in Development or behind authorisation in production; partners get the committed, reviewed file instead.
| Approach | When it fits | Cost | When not to |
|---|---|---|---|
| Hand-written types | Prototype, two endpoints | Silent drift | Anything maintained by more than one person |
| Generated types + typecheck | Monorepo, one SPA | Small build step | Consumers outside the repo |
| + committed spec + breaking diff | Multiple or external consumers | CI step, agreed rules | Throwaway internal tools |
| + per-version documents, Sunset headers, usage telemetry | Many consumers, microservices, partners | Version maintenance | A single SPA consumer |
| + consumer-driven contract tests (Pact) | Critical partner integrations | Test infrastructure, broker | Simple CRUD consumed only by your SPA |
| Versioning style | When it fits | Trade-off |
|---|---|---|
URL segment (/v2/orders) |
Public APIs, easy routing and caching | URLs change |
| Header or media type | Internal APIs wanting stable URLs | Less visible, harder to test in a browser |
| No versions, additive only | Single first-party SPA | Needs discipline and deprecation windows |
On .NET 10, expose the OpenAPI document from ASP.NET Core with the built-in AddOpenApi / MapOpenApi (Microsoft.AspNetCore.OpenApi, available since .NET 9), then generate TypeScript in the build with openapi-typescript, Kiota or NSwag. Regenerate in CI and fail the build if the output changes unexpectedly, and run a breaking-change check (e.g. oasdiff) on the spec. Version the API (URL or header) and keep old contracts until clients move, so generated types for v1 and v2 can coexist. This turns a renamed field into a compile error instead of a production bug.
On the server, a Minimal API with .NET 10's built-in validation (AddValidation() plus DataAnnotations on the request record) returns 400 ValidationProblemDetails automatically and 201 Created with the new DTO on success.
On the client, a small typed API module wraps fetch: it checks res.ok, parses ProblemDetails into a typed ApiError with the errors dictionary, and returns typed DTOs. The React screen uses TanStack Query: useQuery for the list and useMutation for the create, then invalidates the list so it refetches.
The form shows field errors from the server next to each input, a general message for non-field problems, and disables submit while saving. Client checks are only for speed of feedback; the trade-off is a little duplication for a much better UX, with the server as the source of truth.
Prefer additive, backwards-compatible changes: new optional request fields, new response fields, new endpoints, and clients that ignore unknown fields (tolerant readers). Think in semantic versioning terms: additive changes are minor and need no new version; only breaking changes justify a new major version.
For removals or renames: add the new field, mark the old one deprecated in OpenAPI and send Deprecation and Sunset headers, tell consumers (changelog, release notes, developer portal, direct contact for partners), track usage of the old field in telemetry, and remove it only when usage is gone. Risky behaviour changes can roll out behind a feature flag per client.
Introduce a new major version (Asp.Versioning, URL segment or header) only when a change cannot be additive, such as a different resource model. Run at most two majors side by side with a published end date, so versions do not fragment.
How to tell it (STAR)
**S:** On [project], an API refactor renamed one DTO property and the orders grid for [about 300] users showed a blank customer column, with no errors anywhere. **T:** I had to restore it quickly and make sure contract changes could not slip through again. **A:** I confirmed the rename in the Network tab, restored the old property alongside the new one, then set up build-time OpenAPI generation, committed the spec, published generated TypeScript types and added an oasdiff gate plus a frontend typecheck to CI, with an agreed rule that removals need a deprecation period. **R:** In the following [six months] the gate blocked [N] breaking changes before merge and we had [zero] contract-related incidents.
Last updated 23 Nov 2026.