liveBook · Manning

OpenAPI specification

As explained in ASP.NET Core in Action, 3e

An OpenAPI document is a structured document that describes an HTTP API's available URLs, operations, parameters, and data types according to the OpenAPI standard.

OpenAPI is a language-agnostic specification for describing RESTful APIs. An OpenAPI document describes an API’s URLs, how to invoke them, and the data types they return. Tools can use the document to display endpoints, test requests, or generate clients. section 11.1

In an ASP.NET Core minimal API, Swashbuckle uses endpoint metadata to generate the document and middleware to serve it. Add the Swashbuckle.AspNetCore package, register AddEndpointsApiExplorer() and AddSwaggerGen(), and call UseSwagger() after building the app. UseSwaggerUI() adds an optional interface for exploring the document. section 11.1 section 11.2

Listing 11.1 Adding OpenAPI support to a minimal API app using Swashbuckle
using System.Collections.Concurrent;
 
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
 
builder.Services.AddEndpointsApiExplorer();    #1
builder.Services.AddSwaggerGen();              #2
 
WebApplication app = builder.Build();
 
var _fruit = new ConcurrentDictionary<string, Fruit>();
 
app.UseSwagger();                              #3
app.UseSwaggerUI();                            #4
 
app.MapGet("/fruit/{id}", (string id) =>
    _fruit.TryGetValue(id, out var fruit)
        ? TypedResults.Ok(fruit)
        : Results.Problem(statusCode: 404));
 
app.MapPost("/fruit/{id}", (string id, Fruit fruit) =>
    _fruit.TryAdd(id, fruit)
        ? TypedResults.Created($"/fruit/{id}", fruit)
        : Results.ValidationProblem(new Dictionary<string, string[]>
          {
              { "id", new[] { "A fruit with this id already exists" } }
        }));
 
app.Run();
record Fruit(string Name, int Stock);
#1 Adds the endpoint-discovery features of ASP.NET Core that Swashbuckle requires
#2 Adds the Swashbuckle services required for creating OpenApi Documents
#3 Adds middleware to expose the OpenAPI document for your app
#4 Adds middleware that serves the Swagger UI

This minimal fruit API registers the OpenAPI services and middleware alongside its endpoints. section 11.1

Swagger UI is available at /swagger by default. Choose an endpoint, select Try it out, enter parameters, and select Execute to see the response. Compare the documented responses with actual behavior: a GET endpoint that can return 404 needs metadata describing that response as well as its successful response. section 11.2

Listing 11.9 Adding summaries and descriptions to endpoints using WithOpenApi()
using System.Collections.Concurrent;
 
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
 
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
 
WebApplication app = builder.Build();
 
app.UseSwagger();
app.UseSwaggerUI();
 
var _fruit = new ConcurrentDictionary<string, Fruit>();
 
app.MapGet("/fruit/{id}", (string id) =>
    _fruit.TryGetValue(id, out var fruit)
        ? TypedResults.Ok(fruit)
        : Results.Problem(statusCode: 404))
    .WithName("GetFruit")
    .WithTags("fruit")
    .Produces<Fruit>()
    .ProducesProblem(404)
    .WithSummary("Fetches a fruit")                             #1
    .WithDescription("Fetches a fruit by id, or returns 404" +  #2
      " if no fruit with the ID exists")                        #2
    .WithOpenApi();                                             #3
 
app.Run();
record Fruit(string Name, int Stock);
#1 Adds a summary to the endpoint
#2 Adds a description to the endpoint
#3 Exposes the metadata added by summary and description to the OpenAPI description

The fruit endpoint adds response metadata, a summary, and a description to improve its OpenAPI document. section 11.5.1

In this setup, summaries and descriptions added with WithSummary() and WithDescription() also require the Microsoft.AspNetCore.OpenApi package and a call to WithOpenApi(). Alternatively, Swashbuckle can read C# XML documentation comments. In .NET 7, this approach supports static or instance method handlers, but not lambdas or local functions. section 11.5.1 section 11.5.3

NSwag can generate a strongly typed C# client from the document, including request serialization and response deserialization. A document downloaded into the client project is a snapshot: refresh it after API metadata changes, then build the project to regenerate the client. Use the same tool to refresh the document that was used to add it. section 11.4 section 11.4.5

OpenAPI does not describe every API style. Dynamic HATEOAS links, for example, are difficult to describe up front. Tools can also lag behind the specification, so a newer feature may not work throughout the document-generation and client-generation chain. section 11.6.1 section 11.6.3

How ASP.NET Core in Action, 3e covers it

How deep it goes
Explains document generation, endpoint metadata, client refresh, and limitations through practical setup steps.
Examples
Uses a fruit-stock minimal API with GET and POST endpoints and a generated C# client.
What it assumes
Assumes a minimal API application and, for client generation, a simple .NET 7 console application.
What you can do after
Apply it via Swashbuckle, Swagger UI, and NSwag to document and test endpoints and generate a C# client.
How it connects
Connects REST APIs, endpoint metadata, API testing, client generation, and HATEOAS.

Also explained in

Compare how 12 books explain OpenAPI specification →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of ASP.NET Core in Action, 3e. The section links point to the parts of the book it draws on.