Skip to content

10.9 — OpenAPI and Swagger: Swashbuckle, NSwag, Built-in

← Roadmap · Section: 10. Web API Design and REST Prev: 10.8 ProblemDetails · Next: 10.10 CORS

Markers: ⭐ · Confidence: 🔴 · Last reviewed: —


TL;DR

OpenAPI is a machine-readable description of your API. Swagger is the family of tools built on it — most visibly the interactive documentation page.

  • .NET 9 dropped Swashbuckle from the template and shipped built-in Microsoft.AspNetCore.OpenApi, which generates the document but no UI.
  • The document is only as good as what you tell it — [ProducesResponseType] on every action is what makes it useful.
  • Its real value is not the docs page. It is generated clients and contract-first development.

Definitions

Term What it is What it means
OpenAPI a specification A standard JSON/YAML format describing an HTTP API.
Swagger a toolset Tools built on OpenAPI. The name predates the spec's rename.
Swagger UI a web page Interactive documentation rendered from the document.
swagger.json a generated file The OpenAPI document itself.
Swashbuckle a NuGet package The long-standing generator. Reflection-based.
NSwag a NuGet package Generator plus C#/TypeScript client generation.
Microsoft.AspNetCore.OpenApi a built-in package (.NET 9+) Microsoft's first-party document generator. No UI.
Scalar / Redoc UI packages Modern alternatives to Swagger UI.
[ProducesResponseType] an attribute Declares a possible status code and body type.
WithOpenApi() / Produces<T>() minimal API methods The minimal-API equivalents.
IOperationFilter a Swashbuckle interface Hook to modify one operation in the document.
IDocumentTransformer a .NET 9 interface The built-in equivalent, for the whole document.
Contract-first a workflow Write the OpenAPI document first, generate code from it.

The concept

An API without a description forces every consumer to read your source, or guess. OpenAPI writes it down in a format tools can consume:

{
  "openapi": "3.0.1",
  "paths": {
    "/api/orders/{id}": {
      "get": {
        "parameters": [ { "name": "id", "in": "path", "required": true,
                          "schema": { "type": "integer", "format": "int32" } } ],
        "responses": {
          "200": { "content": { "application/json": {
                     "schema": { "$ref": "#/components/schemas/OrderDto" } } } },
          "404": { "description": "Not Found" }
        }
      }
    }
  }
}

The docs page is the least interesting thing this enables. What it actually buys you:

  • Generated clients — a typed C# or TypeScript client, regenerated when the API changes, so a removed field becomes a compile error rather than a runtime undefined.
  • Contract-first development — agree the document, then front-end and back-end build in parallel against it.
  • Contract testing in CI — diff the generated document against the committed one and fail the build on an unintended breaking change.
  • Mock servers — a front-end can develop against a mock generated from the document.

⚠️ That CI diff is the highest-value use and almost nobody does it. Committing swagger.json and failing the build when it changes unexpectedly catches accidental breaking changes before they ship (10.6).


How it works

⚠️ The .NET 9 change

The .NET 9 Web API template no longer includes Swashbuckle. This is a genuinely current interview topic and worth knowing.

The reasons: Swashbuckle had a long period with no active maintainer, and it is reflection-based, which conflicts with Native AOT (21.10).

// .NET 9+ built-in — generates the document
builder.Services.AddOpenApi();

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.MapOpenApi();       // serves /openapi/v1.json
}

⚠️ AddOpenApi() gives you the document and no UI. Hitting /swagger in a new .NET 9 project returns 404, and "where did Swagger go?" is a common first reaction. You add a UI separately:

// Scalar — the modern default
app.MapScalarApiReference();          // package: Scalar.AspNetCore

// Or keep Swagger UI, pointed at the built-in document
app.UseSwaggerUI(o => o.SwaggerEndpoint("/openapi/v1.json", "v1"));

The three generators

Swashbuckle NSwag Built-in (.NET 9+)
Document generation ✅ ✅ ✅
UI included ✅ Swagger UI ✅ ReDoc / Swagger UI ❌ Separate
Client generation ❌ ✅ C# and TypeScript ❌
Native AOT ❌ Reflection ⚠️ Partial ✅
Maintenance ⚠️ Patchy history ✅ Active ✅ Microsoft
Customisation ✅ Mature filter model ✅ ⚠️ Newer, less complete

Choosing: built-in for a new .NET 9+ project, plus Scalar for the UI. NSwag if you want generated clients as part of the build. Swashbuckle for existing projects — it still works, and there is no urgency to migrate.

The part that determines whether it is useful

A generated document tells you a GET returns 200 with an OrderDto. It does not know about your 404, your 409, or the ProblemDetails shape — unless you say so.

// ⚠️ Poor. Swagger shows "200: unknown schema". Every consumer has to ask.
[HttpGet("{id:int}")]
public async Task<IActionResult> Get(int id) { … }

// ✅ Complete. Every outcome documented, so generated clients can be typed.
[HttpGet("{id:int}")]
[ProducesResponseType(typeof(OrderDto), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status403Forbidden)]
public async Task<ActionResult<OrderDto>> Get(int id, CancellationToken ct) { … }

⚠️ ActionResult<T> gives the generator the success type for free — IActionResult does not. That is a practical reason to prefer it beyond compile-time safety (9.3).

⚠️ Nullable reference types drive required in the schema. With NRTs enabled, string Name is required and string? Name is not. Disable NRTs and every property becomes optional, which quietly makes the whole document much less useful.

XML comments

<PropertyGroup>
  <GenerateDocumentationFile>true</GenerateDocumentationFile>
  <NoWarn>$(NoWarn);1591</NoWarn>   <!-- don't demand a comment on every public member -->
</PropertyGroup>
/// <summary>Retrieves a single order by its identifier.</summary>
/// <param name="id">The order identifier.</param>
/// <response code="200">The order was found.</response>
/// <response code="404">No order exists with that identifier.</response>
[HttpGet("{id:int}")]
public async Task<ActionResult<OrderDto>> Get(int id, CancellationToken ct) { … }

⚠️ Without NoWarn 1591 you get a warning for every undocumented public member — hundreds of them, which drowns real warnings and gets TreatWarningsAsErrors switched off.

The deeper detail — security and the production question

An OpenAPI document is a complete map of your API: every endpoint, parameter and shape. That is exactly what someone probing you wants.

⚠️ The default template only maps it in development, and that default is deliberate.

Situation Expose in production?
Public API for third parties ✅ Yes — that is the point
Internal API, private network ⚠️ Fine, low risk
Internal API, internet-facing ❌ No, or behind auth
Anything with [Authorize] endpoints listed ❌ Not anonymously
if (app.Environment.IsDevelopment())
{
    app.MapOpenApi();
    app.MapScalarApiReference();
}
else if (app.Configuration.GetValue<bool>("Api:PublishOpenApi"))
{
    // Deliberate, configured, and still behind authentication
    app.MapOpenApi().RequireAuthorization("ApiDocsPolicy");
}

⚠️ "Just hide it" is not a security control by itself — endpoints are still reachable. The document does not create a vulnerability; it removes the effort of finding one (17.1).

Documenting authentication so the UI's "Try it out" actually works:

builder.Services.AddOpenApi(options =>
{
    options.AddDocumentTransformer((document, context, ct) =>
    {
        document.Components ??= new OpenApiComponents();
        document.Components.SecuritySchemes["Bearer"] = new OpenApiSecurityScheme
        {
            Type   = SecuritySchemeType.Http,
            Scheme = "bearer",
            BearerFormat = "JWT",
            Description  = "Paste the JWT only — Swagger adds the 'Bearer ' prefix."
        };
        return Task.CompletedTask;
    });
});

⚠️ "Do I include the Bearer prefix?" wastes an astonishing amount of collective time. Say it in the description.


Code

A full .NET 9 setup with versioning:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();

builder.Services.AddApiVersioning(o =>
{
    o.DefaultApiVersion = new ApiVersion(1, 0);
    o.ReportApiVersions = true;
})
.AddApiExplorer(o =>
{
    o.GroupNameFormat = "'v'VVV";
    o.SubstituteApiVersionInUrl = true;    // fills {version} in the documented paths
});

// One OpenAPI document per API version
builder.Services.AddOpenApi("v1", options =>
{
    options.AddDocumentTransformer((doc, ctx, ct) =>
    {
        doc.Info = new OpenApiInfo
        {
            Title   = "Orders API",
            Version = "v1",
            Description = "Order management. **v1 is deprecated** — migrate to v2 by 2026-12-31.",
            Contact = new OpenApiContact { Name = "Platform team", Email = "platform@example.com" }
        };
        return Task.CompletedTask;
    });
});

builder.Services.AddOpenApi("v2");

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.MapOpenApi();                       // /openapi/v1.json, /openapi/v2.json
    app.MapScalarApiReference(o => o.Title = "Orders API");
}

app.MapControllers();
app.Run();

A fully documented action:

/// <summary>Creates a new order.</summary>
/// <remarks>
/// Sample request:
///
///     POST /api/v2/orders
///     {
///        "reference": "ORD-2026-0001",
///        "lines": [ { "productId": 7, "quantity": 2 } ]
///     }
/// </remarks>
/// <response code="201">Created. The Location header points at the new order.</response>
/// <response code="400">Validation failed. See the errors dictionary.</response>
/// <response code="409">An order with that reference already exists.</response>
[HttpPost]
[ProducesResponseType(typeof(OrderDto), StatusCodes.Status201Created)]
[ProducesResponseType(typeof(ValidationProblemDetails), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status409Conflict)]
[Consumes(MediaTypeNames.Application.Json)]
[Produces(MediaTypeNames.Application.Json)]
public async Task<ActionResult<OrderDto>> Create(
    CreateOrderRequest request, CancellationToken ct) { … }

The DTO, where the schema quality actually comes from:

/// <summary>A request to create an order.</summary>
public sealed record CreateOrderRequest
{
    /// <summary>Your reference for this order. Must be unique.</summary>
    /// <example>ORD-2026-0001</example>
    [Required, StringLength(50)]
    public string Reference { get; init; } = "";   // non-nullable → required in the schema

    /// <summary>Optional note shown on the delivery paperwork.</summary>
    [StringLength(500)]
    public string? Note { get; init; }             // nullable → optional in the schema

    /// <summary>At least one line is required.</summary>
    [Required, MinLength(1)]
    public IReadOnlyList<OrderLineRequest> Lines { get; init; } = [];
}

The [Range], [StringLength] and [Required] attributes appear in the generated schema, so a consumer sees the constraints without reading your validation code — and a generated client can enforce them before sending (11.4).

Contract testing in CI, which is the payoff:

# Fail the build if the API surface changed without the committed document changing
dotnet build
dotnet tool run swagger tofile --output generated.json bin/Debug/net9.0/Api.dll v1
diff <(jq -S . contracts/v1.json) <(jq -S . generated.json) \
  || { echo "::error::OpenAPI contract changed. Review and commit contracts/v1.json."; exit 1; }

Interview questions

Q: What is OpenAPI and what is Swagger?

OpenAPI is the specification — a machine-readable JSON or YAML description of an API's endpoints, parameters, schemas and responses. Swagger is the family of tools built on it, most visibly Swagger UI, the interactive docs page. The names get used interchangeably because the spec was called Swagger before it was donated and renamed. The interesting part is not the docs page — it is generated clients, contract-first development where front-end and back-end build in parallel against an agreed document, and diffing the generated document in CI to catch unintended breaking changes.

Q: What changed in .NET 9?

The Web API template dropped Swashbuckle and ships Microsoft.AspNetCore.OpenApi instead — Microsoft's first-party generator, which works under Native AOT where the reflection-based Swashbuckle does not. The catch is that it generates the document and no UI, so /swagger returns 404 in a new project and you add Scalar or Swagger UI separately, pointed at /openapi/v1.json. Existing projects on Swashbuckle are fine; there is no forced migration.

Q: How do you make the generated document actually useful?

Mostly by telling it what the generator cannot infer. [ProducesResponseType] for every status code you return, including the error ones with ProblemDetails as the type, so consumers know a 409 is possible and what it looks like. ActionResult<T> rather than IActionResult, because the generic gives the generator the success type for free. XML comments turned on with warning 1591 suppressed. And nullable reference types enabled, since that is what drives required in the schema — with NRTs off, every property is optional and the document is much weaker.

Q: Should the document be exposed in production?

It depends who the API is for. For a public or partner API, yes — that is the point. For an internal internet-facing API, no, or at least behind authentication, because the document is a complete map of every endpoint and parameter, which is precisely what someone probing you wants. The template's development-only default is deliberate. I would be careful how I frame it though: hiding the document is not a security control, since the endpoints are still reachable. It removes convenience for an attacker, not the vulnerability.


Traps ⚠️

  • .NET 9's AddOpenApi() has no UI. /swagger returns 404 until you add one.
  • No [ProducesResponseType] leaves error responses undocumented.
  • IActionResult instead of ActionResult<T> hides the success schema.
  • NRTs disabled makes every property optional in the schema.
  • XML comments without NoWarn 1591 floods the build with warnings.
  • Exposing the document publicly on an internal API hands over a complete endpoint map.
  • Documenting the Bearer prefix ambiguously — say whether to include it.
  • Two DTOs with the same class name in different namespaces collide as schema IDs.
  • SubstituteApiVersionInUrl missing leaves a literal {version} in the paths.
  • Swashbuckle under Native AOT does not work — it is reflection-based.
  • Trusting the document without CI verification — it drifts from reality silently.


Sources