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

📚 Interview question

How do you generate the OpenAPI document at build time in ASP.NET Core with Microsoft.Extensions.ApiDescription.Server? Should you commit the spec, and how do you generate C# or TypeScript clients from it with Kiota or NSwag?

Theory question on generating the OpenAPI document during dotnet build with Microsoft.Extensions.ApiDescription.Server (OpenApiGenerateDocuments, OpenApiDocumentsDirectory, OpenApiGenerateDocumentsOptions, the GetDocument.Insider entry point), whether to commit the spec, and generating C# and TypeScript clients from it with Kiota or NSwag.

Mid-Level Theory Intermediate aspnet-core build-time-generation ci-cd kiota nswag openapi

🎯 Key points

  • Adding Microsoft.Extensions.ApiDescription.Server makes dotnet build write the document (to obj by default) by running the app's entry point with a no-op IServer, so DI, options and transformers apply but no requests are served
  • OpenApiDocumentsDirectory sets the output folder; OpenApiGenerateDocuments turns generation on or off; OpenApiGenerateDocumentsOptions passes tool arguments such as --document-name (which registered document) and --file-name (output name)
  • Start-up code really runs during build: guard database migrations, Key Vault calls and external connections (entry assembly is GetDocument.Insider)
  • Commit the spec so API changes appear as reviewable diffs; CI regenerates it and fails if it differs from the committed file
  • Kiota and NSwag are the main .NET-friendly generators; alternatives include openapi-generator and Refitter (Refit interfaces); generate from the committed spec, not a running server
  • Skip build-time generation for prototypes or single-consumer internal tools where the extra build step and guarded start-up add little

⏱ 30-second answer

Adding the Microsoft.Extensions.ApiDescription.Server package makes dotnet build produce the OpenAPI document. It launches your app's entry point with an inert server, asks the registered document provider for each document, and writes {Project}.json to obj (or to OpenApiDocumentsDirectory). Because your start-up code runs during build, guard anything that connects to databases or Key Vault.

I commit the spec: API changes then show up as diffs in pull requests, CI can fail when the regenerated file differs, and clients are generated from a file rather than a running server. For clients I use Kiota (C#, TypeScript, Go, Python...) or NSwag (C#, TypeScript).

The trade-off: a slightly slower build and a guarded Program.cs, in exchange for a contract you can review, diff and generate from.

🗣 Full answer (senior)

How I would answer this in an interview

"By default the built-in package only generates the document at runtime, when someone hits /openapi/v1.json. For a contract you want it as a file at build time, and that's what Microsoft.Extensions.ApiDescription.Server does. Once it's referenced, an MSBuild target runs after build: it starts your app through a tool called GetDocument.Insider, which runs Program.cs but swaps Kestrel for a server that never listens, then asks the OpenAPI document provider for each registered document and writes it out. By default it lands in obj; I set OpenApiDocumentsDirectory to put it in the project folder and OpenApiGenerateDocumentsOptions to pick the file name.

The catch is that your start-up code really runs. If Program.cs applies EF Core migrations, connects to Key Vault or validates options against a real database, the build does that too, or fails on a build agent with no network. So I guard those with a check on the entry assembly name, or move them out of start-up entirely. I also make sure the document doesn't depend on environment-specific code, otherwise the build-time file and the runtime one differ.

Then I commit the spec. That's the senior part: every pull request that changes the API shows a JSON diff a reviewer can read, and CI rebuilds and runs git diff --exit-code so nobody can change the contract without the file changing. Clients come from that file. For a .NET consumer or a React front end I'd use Kiota, Microsoft's generator, or NSwag if the team already uses it, run in CI so the client is never hand-edited. The mistake I see is generating clients from a running dev server: whatever was running on someone's laptop becomes the contract."


MSBuild properties

Property Purpose Example
OpenApiGenerateDocuments Turn build-time generation on or off false on a fast inner-loop build
OpenApiDocumentsDirectory Output folder (default obj) $(MSBuildProjectDirectory)/openapi
OpenApiGenerateDocumentsOptions Extra arguments to the tool --document-name v1 --file-name orders-api

Commit the spec or not?

Commit it Don't commit
Review API changes visible in PR diffs Must run the app to see changes
CI Can fail on drift and run breaking-change checks Nothing to compare against
Clients Generated from a known file Generated from whatever is running
Cost Occasional merge conflicts in the JSON None

Kiota vs NSwag

Kiota NSwag
Languages C#, TypeScript, Go, Java, PHP, Python, Ruby C#, TypeScript
Style Fluent request builders (client.Orders[id].GetAsync()), small runtime packages Single generated class per client, minimal runtime
Large APIs Can generate a subset with --include-path Generates everything
Fit Many consumers and languages, Microsoft Graph style Teams already on NSwag, simple C#/TS clients

Production example

We committed openapi/orders-api.json and added a CI step that rebuilds and fails on any diff. In the first month it caught 3 pull requests that changed a response shape without anyone noticing, including a property rename that would have broken the mobile app. The TypeScript client is generated with Kiota in the same pipeline, so the front end gets a compile error instead of a runtime undefined.

🔍 What the interviewer is checking

Checks that the candidate treats the OpenAPI document as a build artefact and contract, and understands the practical traps of generating it during build.

Green flags

  • Names Microsoft.Extensions.ApiDescription.Server and the output properties.
  • Knows Program.cs runs during build and guards side effects.
  • Commits the spec and fails CI on drift.
  • Generates clients from the committed file with Kiota or NSwag.

Red flags

  • Downloads the spec from a running dev server for client generation.
  • Hand-edits generated clients.
  • Unaware that start-up code runs at build time.

📚 Learn in depth

1. What happens during build

dotnet build
  -> compile Orders.Api.dll
  -> target GenerateOpenApiDocuments (from Microsoft.Extensions.ApiDescription.Server)
       dotnet GetDocument.Insider.dll --assembly Orders.Api.dll ...
         -> runs Program.Main via the host factory resolver
         -> replaces IServer with a no-op server (never listens)
         -> resolves the document provider registered by AddOpenApi
         -> for each document name: generate and serialise
  -> writes openapi/Orders.Api.json (or obj/ by default)

The app is built and its DI container is created exactly as at runtime, so AddOpenApi options, transformers and JsonSerializerOptions all apply. What doesn't happen is request processing.

2. Guarding start-up side effects

Anything in Program.cs before app.Run() executes. Common offenders:

  • db.Database.Migrate() at start-up
  • AddAzureKeyVault(...) configuration providers calling Azure
  • ValidateOnStart options that require secrets not present on build agents
  • Hosted services: they are not started, but their constructors may run if resolved

The documented trick is to check Assembly.GetEntryAssembly()?.GetName().Name == "GetDocument.Insider" and skip those steps. Better still, move migrations into a separate job (also safer in production).

3. Committing and checking drift

CI
  dotnet build -c Release            (regenerates openapi/*.json)
  git diff --exit-code openapi/      (fails if the committed spec is stale)
  breaking-change check vs main      (oasdiff or similar)
  kiota generate / nswag             (client from the committed file)

The spec becomes part of the review. A reviewer who sees a required property disappear knows to ask about consumers.

4. Client generation

  • Kiota: kiota generate -l CSharp -d openapi/orders-api.json -c OrdersClient -n Orders.Client -o src/Orders.Client. Uses Microsoft.Kiota.* runtime packages for HTTP, serialisation and authentication. kiota-lock.json records the settings so regeneration is reproducible.
  • NSwag: nswag openapi2csclient /input:openapi/orders-api.json /output:OrdersClient.cs or openapi2tsclient; can also run through an nswag.json file or MSBuild.
  • Visual Studio connected services / dotnet openapi wrap NSwag for simple cases.

Generated code is build output. Commit it or generate it in the build, but never edit it by hand; customise through generator settings or partial classes.

Try it yourself

  1. Add Microsoft.Extensions.ApiDescription.Server, set OpenApiDocumentsDirectory, run dotnet build and open the file.
  2. Add throw new Exception() inside an if (!isBuildTimeGeneration) block and confirm the build still succeeds.
  3. Commit the spec, rename a property in a DTO, rebuild and look at git diff.
  4. Generate a C# client with Kiota and call one endpoint from a console app.
  5. Add the git diff --exit-code step to a GitHub Actions or Azure Pipelines workflow.

💻 Code

Project file, guarded start-up and client generation.

<!-- Orders.Api.csproj -->
<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>net10.0</TargetFramework>
    <Nullable>enable</Nullable>
    <!-- write the spec into the repo, not obj/, so it can be committed -->
    <OpenApiDocumentsDirectory>$(MSBuildProjectDirectory)/openapi</OpenApiDocumentsDirectory>
    <OpenApiGenerateDocumentsOptions>--file-name orders-api</OpenApiGenerateDocumentsOptions>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.*" />
    <PackageReference Include="Microsoft.Extensions.ApiDescription.Server" Version="10.0.*">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
    </PackageReference>
  </ItemGroup>
</Project>
// Program.cs
using System.Reflection;

var builder = WebApplication.CreateBuilder(args);

// true when dotnet build is generating the document, not serving requests
var isBuildTimeGeneration = Assembly.GetEntryAssembly()?.GetName().Name == "GetDocument.Insider";

if (!isBuildTimeGeneration)
{
    // needs network and identity that a build agent doesn't have
    builder.Configuration.AddAzureKeyVault(new Uri(builder.Configuration["KeyVault:Uri"]!), new Azure.Identity.DefaultAzureCredential());
}

builder.Services.AddOpenApi();

var app = builder.Build();
app.MapOpenApi();
app.MapGet("/orders/{id:int}", (int id) => TypedResults.Ok(new OrderDto(id, "AU-1001", 129.95m)))
   .WithName("GetOrder");
app.Run();

public sealed record OrderDto(int Id, string Reference, decimal Total);
# CI: fail if the committed spec is stale, then generate a TypeScript client from it
dotnet build src/Orders.Api -c Release
git diff --exit-code src/Orders.Api/openapi/

dotnet tool install --global Microsoft.OpenApi.Kiota
kiota generate -l TypeScript -d src/Orders.Api/openapi/orders-api.json \
  -c OrdersClient -o web/src/clients/orders

⚠ Common mistakes

  • Mistake: Leaving migrations or Key Vault calls unguarded in Program.cs. Why it is wrong: They run during dotnet build, so the build can migrate a real database, or fail on agents that have no network route or identity for those resources. Instead: Guard them with the GetDocument.Insider check, or move migrations to a separate deployment step.
  • Mistake: Not committing the spec. Why it is wrong: API changes are invisible in review and nothing can detect drift or breaking changes. Instead: Commit it and fail CI when the regenerated file differs.
  • Mistake: Generating clients from a running local server. Why it is wrong: The contract becomes whatever branch was running on someone's machine. Instead: Generate from the committed file in CI.
  • Mistake: Hand-editing generated clients. Why it is wrong: The next regeneration silently overwrites the fix. Instead: Change the spec or generator settings; extend with partial classes.
  • Mistake: Having code paths that add endpoints only in some environments. Why it is wrong: The build-time document (generated without your deployment's environment variables) differs from production. Instead: Keep endpoint registration environment-independent, or generate per environment deliberately.
  • Mistake: Pointing several projects, or several target frameworks of one multi-targeted project, at the same OpenApiDocumentsDirectory and file name. Why it is wrong: Parallel builds (dotnet build -m) overwrite each other's file, so the committed spec flips between versions and the drift check fails randomly. Instead: Give each project and document a unique --file-name, and generate from a single target framework.
  • Mistake: Keeping Swashbuckle's SwaggerGen alongside the built-in generator. Why it is wrong: Two document providers confuse the tool; developers have reported no file being produced. Instead: Use one generator.
  • Mistake: Letting the generator package flow to consumers. Why it is wrong: It's build tooling only. Instead: Keep PrivateAssets=all.

🏛 Senior insight: trade-offs

Build-time generation turns the OpenAPI document from a debugging aid into an artefact: something versioned, reviewed and tested like code. The senior judgement is mostly about the side effects of running Program.cs in a build and about where clients come from. I treat start-up side effects as a smell anyway (migrations at start-up race across instances), so the guard often pushes the design in a better direction.

It isn't always worth it. For a prototype whose API changes hourly, or an internal tool with one consumer in the same repository, a runtime document is enough and the extra build step is friction. For anything with external or mobile consumers, the committed spec pays for itself the first time it catches an unintended change.

Option When it fits Cost When not to
Runtime document only Prototypes, internal tools with one consumer No diff, no contract checks Anything with external consumers
Build-time, committed Most APIs with clients Guarded start-up, occasional JSON conflicts Rapid prototyping where the API changes hourly
Design-first (spec written by hand, code follows) Public or partner APIs, multiple teams Two artefacts to keep in step Small internal services
Kiota clients Many languages, large APIs Runtime packages, fluent style to learn Teams standardised on NSwag
NSwag clients Simple C#/TS clients Fewer languages Polyglot consumers
Refitter / openapi-generator Teams that like Refit interfaces, or need a language Kiota lacks Another tool's conventions When Kiota or NSwag already cover your consumers

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions committing the spec and failing CI on drift. Why: Checks the next step: using the committed spec to block breaking changes.
    How to answer

    I make the committed build-time spec the contract and gate pull requests on it:

    1. Drift check: rebuild and fail if the generated spec differs from the committed one.
    2. Breaking-change check: oasdiff breaking compares the PR's spec with main and the last released spec, and fails on removed paths or properties, new required request fields, narrowed enums or changed types.
    3. Lint: Spectral rules for house style (operationIds, ProblemDetails errors, naming).
    4. Versioning: one document per major version (AddOpenApi("v1"), AddOpenApi("v2")), so breaking changes go into a new version while v1 stays frozen.

    The trade-off: CI becomes stricter and occasionally needs a deliberate override, but breaking changes become explicit decisions instead of production incidents.

  2. When: Candidate mentions transformers running during build-time generation. Why: Checks how the document's content is shaped before it is written to disk.
    How to answer

    You register a document with builder.Services.AddOpenApi("v1", o => ...) and serve it with app.MapOpenApi(), which maps /openapi/v1.json (a .yaml route also works in .NET 10). Customisation happens in transformers:

    • Document transformers change the whole document: Info, servers, security schemes.
    • Operation transformers change one operation: add a security requirement or a header.
    • Schema transformers change the schema of one type: formats, examples.

    For JWT you add a bearer scheme to Components.SecuritySchemes and a requirement on operations that have IAuthorizeData metadata. In .NET 10 the output is OpenAPI 3.1 by default (JSON Schema 2020-12, nullability as type arrays) on Microsoft.OpenApi 2.x, so some .NET 9 transformer code needs updating. The trade-off: transformers are explicit and AOT-friendly but you write the plumbing Swashbuckle filters used to give you.

🛠 Real-world problems: how you handle them

Mobile app broke after an unnoticed response rename
Situation
An [ordering] API on .NET 10 with a React web app and a [React Native] mobile app, both using hand-maintained TypeScript types. Mobile releases go through store review, so a broken build stays in users' hands for [days].
Signals
A spike in mobile crash reports after a backend deploy; Application Insights showed 200 responses, but the app read `customerName`, which had been renamed to `customer.name`; no test failed and the pull request review didn't spot it.
Investigation
Compared the runtime OpenAPI document from the previous and current releases by downloading both from staging and diffing them; found the rename and two other silent shape changes; confirmed no committed spec or client generation existed.
Resolution
Immediately added the old property back as a computed field and redeployed. Then added `Microsoft.Extensions.ApiDescription.Server`, committed the spec, added a CI drift check, and replaced hand-written types with a Kiota-generated client in both apps.
Prevention
CI fails if the regenerated spec differs from the committed file; a breaking-change check against `main`; clients generated in CI so a contract change becomes a compile error in the consuming app; PR template asks whether the spec diff is intentional.

How to tell it (STAR)

**S:** At [company] a backend property rename broke our mobile app for [two days] because nothing tied the API to its clients. **T:** I took on making contract changes impossible to miss. **A:** After a quick compatibility fix, I set up build-time OpenAPI generation, committed the spec, added a CI step that fails on drift, and switched both apps to Kiota-generated clients built from that file. **R:** In the first [month] the drift check caught [3] unintended shape changes in review, and we've had [no] contract-related production incidents since.

↩ Usually asked after

More in API Features

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me