DEV Community

Cover image for How to Write Your ASP.NET Core OpenAPI Document on Every Build
Denny
Denny

Posted on Originally published at routebase.dev

How to Write Your ASP.NET Core OpenAPI Document on Every Build

Your ASP.NET Core API already knows everything its docs need. In this tutorial we give it interactive docs in three steps, with one package, one line in Program.cs and one build. Then we make the descriptions clean and look at what to check before you ship.

The last step connects Routebase, which is our product. It's optional, and everything before it works without an account.

You need .NET 10 or .NET 11.

Step 1. Add the package

Start with a new API, or use one you already have. Any app that registers OpenAPI works, and the webapi template already does that with builder.Services.AddOpenApi().

dotnet new webapi -n OrdersApi
cd OrdersApi
dotnet add package Routebase.AspNetCore
Enter fullscreen mode Exit fullscreen mode

Step 2. Add one line to Program.cs

Map the docs page right after var app = builder.Build();.

using Routebase.AspNetCore;

var app = builder.Build();
app.MapRoutebaseApiReference();
Enter fullscreen mode Exit fullscreen mode

Step 3. Run it

dotnet run
Enter fullscreen mode Exit fullscreen mode

Open /routebase on the address dotnet run prints. That's it, your API has docs.

The API reference in the dark theme, with the endpoints grouped by tag on the left and the overview of the API on the right

You get a search, code samples for every endpoint and a playground that calls your API from the browser. The overview downloads the document as JSON, as YAML or as a Postman collection, and Copy as Markdown above each endpoint copies it for a chat with an AI assistant.

Behind the page, the build now writes your OpenAPI document into obj/, as OrdersApi.json and OrdersApi.yaml. The docs read that file, so they show exactly the build you run, and they work in production without a runtime document route.

The first build also prints a one-time hint about linking the project to Routebase. We come back to it in step 6.

Step 4. Make the descriptions clean

The docs can only show what your code declares. Three small changes make the biggest difference.

Say what each endpoint does. A tag groups the endpoint in the navigation, and the summary and the description tell the reader what it does.

app.MapGet("/products/{id:int}", GetProduct)
    .WithTags("Products")
    .WithSummary("Get a product")
    .WithDescription("Returns one product by its ID, or 404 when no product has that ID.");
Enter fullscreen mode Exit fullscreen mode

Let every response show up. Here is a handler the way many of us write it.

app.MapGet("/products/{id:int}", (int id, DataStore db) =>
    db.Products.FirstOrDefault(p => p.Id == id) is { } product
        ? Results.Ok(product)
        : Results.NotFound(new ApiError("NOT_FOUND", "Product not found.")));
Enter fullscreen mode Exit fullscreen mode

Results.Ok returns IResult, so the OpenAPI generator never sees Product, and on its own the docs would show a bare 200 without a body. The package reads these handlers while your app compiles and adds both responses. Your docs now show a 200 with Product and a 404 with ApiError, and you didn't touch the handler.

When the build can't read a handler, for example because one path returns an anonymous object, your IDE marks it and offers a fix. Use TypedResults switches the handler to typed results, and Extract a record for the anonymous response turns new { status = "ok" } into a record while the JSON stays the same. For controllers, the fix adds the missing [ProducesResponseType] attributes.

The quick-fix menu on a minimal API handler that returns an anonymous object, with Extract a record for the anonymous response and Use TypedResults

Describe your models. Your schemas take their descriptions from XML comments. Switch on the documentation file, and the second line keeps the compiler from asking for a comment on every public member.

<PropertyGroup>
  <GenerateDocumentationFile>true</GenerateDocumentationFile>
  <NoWarn>$(NoWarn);CS1591</NoWarn>
</PropertyGroup>
Enter fullscreen mode Exit fullscreen mode
/// <summary>A product in the catalog.</summary>
/// <param name="Id">The product ID.</param>
/// <param name="Name">The name shown in the shop.</param>
public record Product(int Id, string Name);
Enter fullscreen mode Exit fullscreen mode

Step 5. Check three things before you ship

The build starts your app. To read your endpoints, the build runs Program.cs in the Production environment without its runtime configuration. If a registration needs a connection string or a secret, skip it during that run.

if (!RoutebaseOpenApi.IsGeneratingDocument)
{
    builder.Services.AddSingleton(new PaymentClient(builder.Configuration["Payments:ApiKey"]!));
}
Enter fullscreen mode Exit fullscreen mode

Commit the document. Nobody commits obj/, so move the documents into a folder of their own.

<PropertyGroup>
  <OpenApiDocumentsDirectory>$(MSBuildProjectDirectory)/openapi</OpenApiDocumentsDirectory>
</PropertyGroup>
Enter fullscreen mode Exit fullscreen mode

Build again and commit the openapi folder. From now on, a pull request that renames a field also changes these files, so your reviewers see the API change right next to the code change.

Decide who sees the docs. The page works in production. If you only want it locally, map it inside if (app.Environment.IsDevelopment()). If you want it online but private, add .RequireAuthorization().

Step 6. Connect Routebase

From here on we use Routebase. You can try it from your docs page first and then let CI do it on every build.

From localhost. While your docs run on localhost, their header shows a menu called Open in Routebase.

The header of the API reference with the Open in Routebase menu open, listing Rate and lint, Mock server, Publish docs, Smoke tests and Keep in sync on every build, none of them run yet

Each action opens a Routebase tab and takes your document along:

  • Rate and lint grades the design of your API and checks it against your style guide.
  • Mock server starts a stand-in for your API that answers from the document, so a frontend can start before the backend is done.
  • Publish docs puts your docs on a hosted docs portal.
  • Smoke tests creates one quick test per endpoint and runs it against the app on your machine, straight from your browser.

Without an account you sign up first, and until then the document waits in your browser. After an action, your docs show the result next to the menu. Here the API scored a C with 55 points, the mock server is running, and all six smoke tests passed.

The header of the API reference with the status chip reading In Routebase, Score C 55, Mock running and Tests 6/6 passed, and the Open in Routebase menu with the result of each action

In CI. Now we link the build to your API in Routebase, so every build does this without a click. The quickest way is Keep in sync on every build in the same menu, or Connect build… on a spec in Routebase. It fills in your IDs and creates a build key with one click. You can also write the lines yourself.

<PropertyGroup>
  <RoutebaseProject>3f2b6c1e-0000-0000-0000-000000000000</RoutebaseProject>
</PropertyGroup>
<ItemGroup>
  <RoutebaseSpecLink Include="Orders API" />
</ItemGroup>
Enter fullscreen mode Exit fullscreen mode

The key goes into your CI as the secret ROUTEBASE_API_KEY. The package reads it only from that environment variable, so it never ends up in a committed file.

name: build

on:
  push:
    branches: [main]
  pull_request:

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-dotnet@v4
        with:
          dotnet-version: 10.0.x
      - run: dotnet build
        env:
          ROUTEBASE_API_KEY: ${{ secrets.ROUTEBASE_API_KEY }}
Enter fullscreen mode Exit fullscreen mode

From now on, your CI build does four things on its own:

  • Every merge updates Routebase. A build of main pushes the document into your API in Routebase.
  • Every pull request shows its effect. With the key set, its build lists what a push would change, breaking changes included, before you merge.
  • Every push gets a grade. The API rating scores your API from 0 to 100 with a grade from A to E, and the result lands in your IDE's error list. The rating is part of the Pro plan.
  • Every breaking change waits for a decision. A change that breaks existing clients, such as a removed endpoint, fails the build. The error links to a page in Routebase where you accept the change, reject it or open a branch with a merge request.

In the build log, these messages carry codes that start with RB, the same way compiler warnings start with CS. The guide explains every one of them.

The Problems panel of the IDE after a build, with the Routebase rating summary, the failed rating checks and the style-guide findings, one entry each and all from the source dotnet

Wrapping up

That's the whole path. One package, one line and one build give you docs, a few annotations make them clean, and Routebase checks every change against them.

The full guide covers every setting and every build message. The package is on NuGet, and the post on our blog shows the rest of it with more screenshots. You can start on the Free plan, and the rating comes with the 14-day Pro trial, which needs no credit card. Send questions and feedback to support@routebase.dev.

Top comments (0)