TExcelTAD
Home › ASP.NET Core › OpenAPI Documents

OpenAPI Documents

An OpenAPI document is a machine-readable JSON description of your HTTP API: every path, its parameters, request bodies, response codes and the shape of the JSON it returns. Tools use it to render interactive documentation, generate client SDKs (C#, TypeScript, …), and run contract tests.

Built-in support in .NET 9

Starting with .NET 9, ASP.NET Core generates OpenAPI documents itself through the Microsoft.AspNetCore.OpenApi package. The webapi template already references it; for other projects add it:

bash · try it yourself
$ dotnet add package Microsoft.AspNetCore.OpenApi
info : Adding PackageReference for package 'Microsoft.AspNetCore.OpenApi' into project '/home/dev/TodoApi/TodoApi.csproj'.
info : PackageReference for package 'Microsoft.AspNetCore.OpenApi' version '9.0.10' added to file '/home/dev/TodoApi/TodoApi.csproj'.

Two lines turn it on — one registers the document generator, the other maps an endpoint that serves it:

csharp
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddOpenApi();               // document named "v1"

var app = builder.Build();

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

var todos = new List<Todo> { new(1, "Write docs", false) };

app.MapGet("/todos/{id:int}", (int id) =>
        todos.FirstOrDefault(t => t.Id == id) is Todo t
            ? Results.Ok(t)
            : Results.NotFound())
   .WithName("GetTodo")
   .WithSummary("Get a todo by id")
   .Produces<Todo>(StatusCodes.Status200OK)
   .Produces(StatusCodes.Status404NotFound);

app.Run();

record Todo(int Id, string Title, bool IsDone);

Note: Earlier templates (up to .NET 8) shipped Swashbuckle (AddSwaggerGen/UseSwaggerUI). The .NET 9 templates no longer include it. Swashbuckle still works if you add it yourself, but the built-in generator is now the default path.

Reading the document

bash · try it yourself
$ curl -s localhost:5000/openapi/v1.json
{
  "openapi": "3.0.1",
  "info": {
    "title": "TodoApi | v1",
    "version": "1.0.0"
  },
  "servers": [
    {
      "url": "http://localhost:5000"
    }
  ],
  "paths": {
    "/todos/{id}": {
      "get": {
        "tags": [
          "TodoApi"
        ],
        "summary": "Get a todo by id",
        "operationId": "GetTodo",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": {
              "type": "integer",
              "format": "int32"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Todo"
                }
              }
            }
          },
          "404": {
            "description": "Not Found"
          }
        }
      }
    }
  },
  "components": {
    "schemas": {
      "Todo": {
        "required": [
          "id",
          "title",
          "isDone"
        ],
        "type": "object",
        "properties": {
          "id": {
            "type": "integer",
            "format": "int32"
          },
          "title": {
            "type": "string"
          },
          "isDone": {
            "type": "boolean"
          }
        }
      }
    }
  },
  "tags": [
    {
      "name": "TodoApi"
    }
  ]
}

Notice where each part came from:

Document field Source in code
paths./todos/{id} the route template (the :int constraint becomes integer/int32)
operationId .WithName("GetTodo")
summary .WithSummary(...) (or .WithDescription(...) for longer text)
responses .Produces<Todo>(200), .Produces(404)
components.schemas.Todo the Todo record, with camelCase property names
tags defaults to the app name; override with .WithTags("Todos")

Tip: Return TypedResults with a Results<Ok<Todo>, NotFound> return type and the generator can infer the responses without any .Produces calls.

How the generator works

Under the hood, the framework walks the endpoint metadata (route, parameters, attached names, declared responses) and serializes a JSON tree. Here is a much smaller version of that idea, built with System.Text.Json.Nodes:

csharp · try it yourself
using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Text.Json.Nodes;

var endpoints = new List<Endpoint>
{
    new("GET", "/todos", "ListTodos", new[] { 200 }),
    new("POST", "/todos", "CreateTodo", new[] { 201, 400 }),
    new("DELETE", "/todos/{id}", "DeleteTodo", new[] { 204, 404 }),
};

var paths = new JsonObject();
foreach (var e in endpoints)
{
    var responses = new JsonObject();
    foreach (int code in e.Codes)
        responses[code.ToString()] = new JsonObject { ["description"] = Describe(code) };

    if (paths[e.Route] is not JsonObject item)
        paths[e.Route] = item = new JsonObject();
    item[e.Method.ToLowerInvariant()] = new JsonObject
    {
        ["operationId"] = e.Name,
        ["responses"] = responses,
    };
}

var doc = new JsonObject
{
    ["openapi"] = "3.0.1",
    ["info"] = new JsonObject { ["title"] = "TodoApi | v1", ["version"] = "1.0.0" },
    ["paths"] = paths,
};
Console.WriteLine(doc.ToJsonString(new JsonSerializerOptions { WriteIndented = true }));

static string Describe(int code) => code switch
{
    200 => "OK", 201 => "Created", 204 => "No Content",
    400 => "Bad Request", 404 => "Not Found", _ => "Other",
};

record Endpoint(string Method, string Route, string Name, int[] Codes);
{
  "openapi": "3.0.1",
  "info": {
    "title": "TodoApi | v1",
    "version": "1.0.0"
  },
  "paths": {
    "/todos": {
      "get": {
        "operationId": "ListTodos",
        "responses": {
          "200": {
            "description": "OK"
          }
        }
      },
      "post": {
        "operationId": "CreateTodo",
        "responses": {
          "201": {
            "description": "Created"
          },
          "400": {
            "description": "Bad Request"
          }
        }
      }
    },
    "/todos/{id}": {
      "delete": {
        "operationId": "DeleteTodo",
        "responses": {
          "204": {
            "description": "No Content"
          },
          "404": {
            "description": "Not Found"
          }
        }
      }
    }
  }
}

Adding a documentation UI

The built-in package only produces JSON. To browse and try the API in a browser, add a UI that reads /openapi/v1.json. Two popular choices:

UI Package Setup
Scalar Scalar.AspNetCore app.MapScalarApiReference(); → /scalar/v1
Swagger UI Swashbuckle.AspNetCore.SwaggerUi app.UseSwaggerUI(o => o.SwaggerEndpoint("/openapi/v1.json", "v1"));

Both should normally be mapped only in Development, like MapOpenApi above.

You can also produce the document at build time (handy for generating clients in CI) by adding the Microsoft.Extensions.ApiDescription.Server package; dotnet build then writes TodoApi.json into the output folder.

Customizing the document

Document transformers let you edit the generated document — add a description, servers, or security schemes:

csharp
builder.Services.AddOpenApi(options =>
{
    options.AddDocumentTransformer((document, context, cancellationToken) =>
    {
        document.Info.Description = "Manage your todo items.";
        document.Info.Contact = new() { Name = "API Team", Email = "api@example.com" };
        return Task.CompletedTask;
    });
});

Test yourself

With AddOpenApi() and MapOpenApi() in .NET 9, where is the document served by default?

  1. /swagger/v1/swagger.json
  2. /api-docs
  3. /openapi/v1.json
  4. /openapi

Which call sets the operationId of a minimal API endpoint?

  1. WithSummary
  2. WithName
  3. WithTags
  4. Produces

What does Microsoft.AspNetCore.OpenApi provide on its own?

  1. Only the JSON document, not an interactive UI
  2. A Swagger UI page at /swagger
  3. A Scalar UI page
  4. Generated C# client code