How to Interact with the Backend API β
If you're building a Serious Backendβ’, chances are that you're going to need an OpenAPI specification as an output for a number of reasons.
First is typically to generate the client TypeScript bindings. Yes, even if you're using TypeScript on the backend, this makes sense because the frontend model is typically only a subset of the backend model and the OpenAPI interface is the boundary between front- and back-ends.
Second is that many platforms like AWS API Gateway and Google Cloud API Gateway consume OpenAPI specs. If you are building an enterprise API or any sort of API where you'll want to implement an API gateway, you'll want OpenAPI. So even if your frontend is a TypeScript React, Vue, or Svelte application, it makes sense to use the OpenAPI bindings to generate the clients if an API gateway is in the system design.
Third is that OpenAPI can be the foundation of your externally facing APIs and documentation generation using tools like Redocly and Mintlify. If you're just building a simple, self-contained web app, then it isn't relevant. But if you're building a serious product (probably why you're using Nest.js and curious about .NET), then OpenAPI tooling is key.
.NET OpenAPI support
Since .NET 9, Microsoft ships first-party OpenAPI tooling via Microsoft.AspNetCore.OpenApi and build-time export via Microsoft.Extensions.ApiDescription.Server. It works for both Minimal APIs and Controllers; below we'll walk through a clean Minimal API pattern (IEndpoint + IEndpointHandler) paired with Kubb on the TypeScript side.
What .NET 11 changes
ASP.NET Core 11 generates OpenAPI 3.2 by default. If your client generator or OpenAPI validator doesn't speak 3.2 yet, pin 3.1 both in AddOpenApi (for the live /openapi/v1.json route) and via --openapi-version OpenApi3_1 in <OpenApiGenerateDocumentsOptions> (for build-time export).
Authoring Endpoints (IEndpoint + IEndpointHandler) β
Minimal APIs (not Controller APIs)
This walkthrough uses ASP.NET Core Minimal APIs, not Controller APIs. If you prefer controllers, the .csproj OpenAPI export and Kubb setup below work the same way -- only the endpoint authoring style changes.
One downside of putting every route directly into Program.cs is that it turns into a giant file fast. A clean, lightweight pattern (without pulling in a third-party framework) is to introduce two tiny interfaces: IEndpoint for HTTP binding, and IEndpointHandler -- which is just an empty marker interface so Scrutor can find and register every handler into DI automatically (see Reflection):
// IEndpoint.cs
public interface IEndpoint {
void MapEndpoints(IEndpointRouteBuilder endpoints);
}
// IEndpointHandler.cs (marker interface -- Scrutor uses it to auto-register handlers)
public interface IEndpointHandler { }
// Program.cs
builder.Services
.AddOpenApi(options => {
options.OpenApiVersion = OpenApiSpecVersion.OpenApi3_1;
})
.Scan(scan => scan
.FromApplicationDependencies()
.AddClasses(c => c.AssignableTo<IEndpoint>())
.AsImplementedInterfaces()
.WithTransientLifetime()
.AddClasses(c => c.AssignableTo<IEndpointHandler>())
.AsSelf()
.WithTransientLifetime()
);
var app = builder.Build();
if (app.Environment.IsDevelopment()) {
app.MapOpenApi();
}
// Register every IEndpoint discovered by Scrutor
foreach (var endpoint in app.Services.GetRequiredService<IEnumerable<IEndpoint>>()) {
endpoint.MapEndpoints(app);
}
app.Run();Now each feature lives in its own file.
Return concrete TypedResults (Ok<List<Contact>>, Created<Contact>) instead of untyped IResult so OpenAPI infers the exact HTTP status codes and response schemas automatically, and add .WithName(...) so the generated TypeScript client gets clean function names (listContacts, createContact):
using Microsoft.AspNetCore.Http.HttpResults;
public class ContactsEndpoint : IEndpoint {
public void MapEndpoints(IEndpointRouteBuilder endpoints) {
var group = endpoints.MapGroup("/contacts").WithTags("Contacts");
group.MapGet("/", ListAsync).WithName("ListContacts");
group.MapPost("/", CreateAsync).WithName("CreateContact");
}
private static Ok<List<Contact>> ListAsync(ContactsHandler handler) =>
handler.List();
private static Created<Contact> CreateAsync(
CreateContactRequest request,
ContactsHandler handler
) => handler.Create(request);
}
public class ContactsHandler : IEndpointHandler {
private static readonly List<Contact> Contacts = [
new(1, "Ada", "Lovelace"),
new(2, "Alan", "Turing")
];
public Ok<List<Contact>> List() => TypedResults.Ok(Contacts);
public Created<Contact> Create(CreateContactRequest request) {
var contact = new Contact(Contacts.Count + 1, request.FirstName, request.LastName);
Contacts.Add(contact);
return TypedResults.Created($"/contacts/{contact.Id}", contact);
}
}
/// <summary>A contact stored by the API.</summary>
/// <param name="Id">Unique contact identifier.</param>
/// <param name="FirstName">Contact's first name.</param>
/// <param name="LastName">Contact's last name.</param>
public record Contact(int Id, string FirstName, string LastName);
/// <summary>Payload for creating a contact.</summary>
/// <param name="FirstName">Contact's first name.</param>
/// <param name="LastName">Contact's last name.</param>
public record CreateContactRequest(string FirstName, string LastName);Separating the endpoint from the handler looks like a bit of ceremony on a toy example, but long term helps projects scale in an orderly manner; HTTP route wiring stays thin, handlers are plain C# classes you can unit test directly, and every new endpoint follows one predictable shape.
Generating Spec Files at Build Time β
Add Microsoft.Extensions.ApiDescription.Server (and Scrutor) to the API project:
dotnet package add Microsoft.Extensions.ApiDescription.Server
dotnet package add ScrutorThen configure the .csproj to emit the OpenAPI JSON file on dotnet build and export your XML doc comments into the spec:
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net11.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<!-- π Emit XML doc comments so OpenAPI includes them as descriptions -->
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<NoWarn>$(NoWarn);CS1591</NoWarn>
<!-- π Write the OpenAPI JSON straight into the frontend project -->
<OpenApiDocumentsDirectory>../../typescript/openapi-client/src/api</OpenApiDocumentsDirectory>
<OpenApiGenerateDocumentsOptions>--file-name api-spec --openapi-version OpenApi3_1</OpenApiGenerateDocumentsOptions>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)' == 'Release'">
<OpenApiGenerateDocuments>false</OpenApiGenerateDocuments>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="11.0.0" />
<PackageReference Include="Microsoft.Extensions.ApiDescription.Server" Version="11.0.0">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Scrutor" Version="7.0.0" />
</ItemGroup>
</Project>Getting XML comments into your OpenAPI spec
Two lines in <PropertyGroup> do the heavy lifting:
<GenerateDocumentationFile>true</GenerateDocumentationFile>tells the compiler to emit XML comments soMicrosoft.AspNetCore.OpenApi's source generator copies your/// <summary>and/// <param>docs into the OpenAPIdescriptionfields (which then become JSDoc comments in TypeScript).<NoWarn>$(NoWarn);CS1591</NoWarn>is optional, but saves you from compiler warnings on every public class or member that doesn't have an XML comment yet.
Run dotnet build and .NET writes api-spec.json directly to the configured directory:
"Contact": {
"required": ["id", "firstName", "lastName"],
"type": "object",
"properties": {
"id": {
"type": ["integer", "string"],
"description": "Unique contact identifier.",
"format": "int32"
},
"firstName": {
"type": "string",
"description": "Contact's first name."
},
"lastName": {
"type": "string",
"description": "Contact's last name."
}
},
"description": "A contact stored by the API."
}Generating Client Bindings with Kubb β
On the frontend / TypeScript side, tools like Kubb takes that OpenAPI JSON and generates typed models and fetch clients (plus optional TanStack Query hooks or Zod schemas if you want them).
Install Kubb and the TypeScript + Fetch plugins:
npm install -D kubb @kubb/plugin-ts @kubb/plugin-fetchAdd kubb.config.ts:
import { defineConfig } from "kubb";
import { pluginTs } from "@kubb/plugin-ts";
import { pluginFetch } from "@kubb/plugin-fetch";
export default defineConfig({
input: "./src/api/api-spec.json",
output: {
path: "./src/api/generated",
clean: true,
},
plugins: [
pluginTs({
output: { path: "./types", mode: "directory" },
enum: { type: "asConst" },
optionalType: "questionTokenAndUndefined",
}),
pluginFetch({
baseURL: "http://localhost:5000",
output: { path: "./clients", mode: "directory" },
}),
],
});Add scripts to package.json:
"scripts": {
"generate": "kubb generate",
"generate:watch": "kubb generate --watch"
}Run npm run generate and Kubb outputs strongly typed models (with JSDoc comments carried straight over from your C# XML comments) and ready-to-call fetch clients:
// Generated: src/api/generated/types/Contact.ts
/** @description A contact stored by the API. */
export type Contact = {
/** @description Unique contact identifier. */
id: number | string;
/** @description Contact's first name. */
firstName: string;
/** @description Contact's last name. */
lastName: string;
};
// Calling the generated client in your app
import { createContact } from "./api/generated/clients/createContact";
import { listContacts } from "./api/generated/clients/listContacts";
const { data: created } = await createContact({
body: { firstName: "Charles", lastName: "Babbage" },
});
const { data: contacts } = await listContacts();Hands-free regeneration during dev
Pair dotnet watch on the backend with npm run generate:watch (or wire both into .NET Aspire). Every time you edit a C# endpoint or record and hit save, the OpenAPI spec updates and Kubb regenerates your TypeScript types and client functions automatically.
Try the Sample Projects β
This repo includes a working end-to-end sample of the exact pipeline above:
| Sample | Location | Command |
|---|---|---|
.NET 11 Minimal API (IEndpoint + Scrutor + OpenAPI) | src/csharp/openapi-api | dotnet build src/csharp/openapi-api |
| TypeScript Kubb Client | src/typescript/openapi-client | npm install && npm run generate && npm run typecheck |
Further Reading β
- Full starter template (
zeeq-ai/zeeq-tmpl) with Minimal API, Scrutor, Aspire, OpenAPI, and Kubb - The Unexpected AI Stack: C# + .NET (Part 2 -- Minimal API &
IEndpoint) - The Unexpected AI Stack: C# + .NET (Part 3 -- OpenAPI & Kubb.dev)
- Official ASP.NET Core OpenAPI docs
