📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

Your React frontend and ASP.NET Core API are maintained by different people, and DTO changes keep breaking the UI in production. How would you set up a contract pipeline: generating the OpenAPI document at build time in .NET 10, generating a typed TypeScript client from it, catching breaking changes in CI, and deciding what is allowed to change without a new API version?

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.

Mid-Level Theory Intermediate api-contracts aspnet-core ci-cd frontend openapi typescript

🎯 Key points

  • Microsoft.AspNetCore.OpenApi (AddOpenApi / MapOpenApi) produces OpenAPI 3.1 by default in .NET 10, but only as accurate as the metadata: TypedResults / Produces, nullable reference types, required members
  • Build-time document via Microsoft.Extensions.ApiDescription.Server, committed to the repo so every change shows in the PR diff
  • Generate TypeScript types or a client (openapi-typescript + openapi-fetch, Orval, NSwag, Kiota) as a CI step that runs on every API spec change, never hand-written DTOs
  • CI runs a breaking-change diff (e.g. oasdiff) against main and fails on removed fields, new required inputs or type changes
  • Frontend typecheck in the same pipeline turns contract drift into a build failure
  • Additive changes are safe; removals, renames and tighter validation need a deprecation window (Deprecation/Sunset headers) or a new version (Asp.Versioning)
  • Separate repos or many consumers: publish the spec or generated client as a versioned package and keep one OpenAPI document per API version
  • Expose the runtime /openapi endpoint only in non-production or behind authorisation; the committed file is the contract

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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.OpenApi package generates OpenAPI 3.1, and if I add Microsoft.Extensions.ApiDescription.Server, the document is written to disk on every build. I commit that JSON file. Now a pull request that renames customerName to customer shows a one-line change in openapi.json that reviewers can't miss.

On the frontend, a script generates types from that file. I like openapi-typescript with openapi-fetch because 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 IResult without metadata, or nullable reference types are off, the spec says everything is optional or unknown and the generated types are useless. So I use TypedResults, 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."


The pipeline

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

Choosing a generator

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

What can change safely

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

Production example

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.

🔍 What the interviewer is checking

Checks whether the candidate can stop frontend/backend contract drift with a practical pipeline rather than relying on communication.

Green flags

  • Makes the OpenAPI document the single source of truth and generates TypeScript from it
  • Knows .NET 10's built-in OpenAPI support and build-time generation
  • Ensures the spec is accurate (TypedResults, nullable, required)
  • Adds a breaking-change gate in CI and defines what counts as breaking
  • Scales the approach to monorepo vs separate repos and external consumers

Red flags

  • Relies on 'telling the frontend team' about changes
  • Hand-copies DTOs into TypeScript
  • Thinks Swagger UI alone solves the problem
  • Cannot say which changes are breaking

📚 Learn in depth

1. Where the document comes from

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.

2. OpenAPI 3.1 and JSON Schema

.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.

3. Build-time generation

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.

4. Detecting breaking changes

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.

5. Monorepo vs separate repos

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.

6. Limits

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.

Try it yourself

  1. Add AddOpenApi() and MapOpenApi() to a Minimal API and open /openapi/v1.json.
  2. Add Microsoft.Extensions.ApiDescription.Server, build, and find the generated file.
  3. Run npx openapi-typescript openapi.json -o src/api-types.ts and use the types with openapi-fetch.
  4. Rename a DTO property, rebuild, regenerate, and watch tsc fail in the React code.
  5. Run oasdiff breaking between the old and new spec and read the report.
  6. Turn off nullable reference types and compare the generated schema.

💻 Code

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

⚠ Common mistakes

  • Mistake: Hand-writing TypeScript interfaces that mirror C# DTOs. Why it is wrong: They drift silently and only fail at runtime. Instead: Generate types from the OpenAPI document in the frontend build.
  • Mistake: Returning bare 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>().
  • Mistake: Leaving nullable reference types off. Why it is wrong: Every property looks nullable or none do, so generated types lie. Instead: Enable nullable and use required members.
  • Mistake: Not committing the generated spec. Why it is wrong: Reviewers never see contract changes, and there is no baseline for diffing. Instead: Commit it and fail CI if it is stale.
  • Mistake: Editing generated client code by hand. Why it is wrong: The next generation overwrites it. Instead: Wrap generated code in your own small module.
  • Mistake: Treating every change as breaking, or none. Why it is wrong: Teams either version constantly or break clients. Instead: Agree rules: additive is safe; removals, renames and tighter requests need deprecation or a new version.
  • Mistake: Using a generator that does not support OpenAPI 3.1. Why it is wrong: Nullable and other schemas are misread. Instead: Check generator support or emit 3.0 explicitly.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate is asked for the basic options for keeping TypeScript types in sync. Why: Checks the simpler baseline before the full pipeline.
    How to answer

    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.

  2. When: Candidate uses the generated client in a React screen. Why: Checks how generated types combine with error handling and ProblemDetails in a real screen.
    How to answer

    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.

  3. When: Candidate mentions breaking changes or deprecation windows. Why: Checks API evolution rules, deprecation and versioning strategy.
    How to answer

    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.

🛠 Real-world problems: how you handle them

Renamed DTO property blanks the customer column in production
Situation
A React + ASP.NET Core back-office app maintained by [two teams in separate repos], with [about 300] internal users and weekly releases.
Signals
After an API release, the orders grid showed an empty Customer column; no errors in the console because `undefined` rendered as blank. Support tickets arrived within [an hour]. Application Insights showed normal 200 responses.
Investigation
Compared responses in the dev tools Network tab with the frontend's hand-written `Order` interface: the API now returned `customer` instead of `customerName` after a refactor. Git history showed the rename in a PR with no frontend reviewer. No spec was committed, so nothing showed the contract change.
Resolution
Immediately: re-added `customerName` to the DTO alongside `customer` and redeployed the API. Properly: generated the OpenAPI document at build time and committed it, published generated TypeScript types as a versioned npm package, added an oasdiff gate to the API pipeline and a typecheck to the frontend pipeline.
Prevention
Breaking-change CI gate with an agreed evolution policy, CODEOWNERS so frontend reviewers see spec changes, deprecation headers for old fields, a Playwright smoke test asserting key grid columns are populated.

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.

More in SPA Integration

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me