Overview of OpenAPI support in ASP.NET Core API apps (original) (raw)

ASP.NET Core supports the generation of OpenAPI documents in controller-based and minimal APIs apps. The OpenAPI specification is a programming language-agnostic standard for documenting HTTP APIs. This standard is supported in ASP.NET Core apps through a combination of built-in APIs and open-source libraries. There are three key aspects to OpenAPI integration in an application:

ASP.NET Core apps provide built-in support for generating information about endpoints in an app via the Microsoft.AspNetCore.OpenApi package.

The following code is generated by the ASP.NET Core minimal web API template and uses OpenAPI:

using Microsoft.AspNetCore.OpenApi;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddOpenApi();

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.MapOpenApi();
}

app.UseHttpsRedirection();

var summaries = new[]
{
    "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};

app.MapGet("/weatherforecast", () =>
{
    var forecast = Enumerable.Range(1, 5).Select(index =>
        new WeatherForecast
        (
            DateTime.Now.AddDays(index),
            Random.Shared.Next(-20, 55),
            summaries[Random.Shared.Next(summaries.Length)]
        ))
        .ToArray();
    return forecast;
})
.WithName("GetWeatherForecast");

app.Run();

internal record WeatherForecast(DateTime Date, int TemperatureC, string? Summary)
{
    public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
}

In the preceding highlighted code:

Microsoft.AspNetCore.OpenApi NuGet package

The Microsoft.AspNetCore.OpenApi package provides the following features:

To use the Microsoft.AspNetCore.OpenApi package, add it as a PackageReference to a project file:

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net9.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>

  <PropertyGroup>
    <OpenApiGenerateDocuments>true</OpenApiGenerateDocuments>
    <OpenApiDocumentsDirectory>$(MSBuildProjectDirectory)</OpenApiDocumentsDirectory>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="9.0.*-*" />
    <PackageReference Include="Microsoft.Extensions.ApiDescription.Server" Version="9.0.*-*">
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
      <PrivateAssets>all</PrivateAssets>
    </PackageReference>
  </ItemGroup>

</Project>

To learn more about the Microsoft.AspNetCore.OpenApi package, see Generate OpenAPI documents.

Microsoft.Extensions.ApiDescription.Server NuGet package

The Microsoft.Extensions.ApiDescription.Server package provides support for generating OpenAPI documents at build time and serializing them.

To use Microsoft.Extensions.ApiDescription.Server, add it as a PackageReference to a project file. Document generation at build time is enabled by setting the OpenApiGenerateDocuments property. By default, the generated OpenAPI document is saved to the obj directory, but you can customize the output directory by setting the OpenApiDocumentsDirectory property.

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net9.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>

  <PropertyGroup>
    <OpenApiGenerateDocuments>true</OpenApiGenerateDocuments>
    <OpenApiDocumentsDirectory>$(MSBuildProjectDirectory)</OpenApiDocumentsDirectory>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="9.0.*-*" />
    <PackageReference Include="Microsoft.Extensions.ApiDescription.Server" Version="9.0.*-*">
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
      <PrivateAssets>all</PrivateAssets>
    </PackageReference>
  </ItemGroup>

</Project>

API v. API operation v. API endpoint

The following sections explain the differences between an API, an API endpoint, and an API operation in the context of ASP.NET Core and OpenAPI documentation.

API (Application Programming Interface)

An API is a set of rules and protocols for building and interacting with software applications. It defines how different software components should communicate. In general web development, "API" typically refers to a web service that exposes functionality over HTTP.

In ASP.NET Core, an API is usually built using controllers or minimal APIs, which handle incoming HTTP requests and return responses.

ASP.NET Core's internal naming conventions sometimes use "API" differently. For instance, in API Explorer, an "ApiDescription" actually represents an API Operation rather than the full API service. This distinction reflects internal naming conventions and sometimes differ from the broader definition used here.

See Introduction to the ApiExplorer in ASP.NET Core for more information on API Explorer.

API Operation

An API operation represents a specific action or capability that an API provides. In ASP.NET Core, this corresponds to:

Each operation is defined by its HTTP method (GET, POST, PUT, etc.), path, parameters, and responses.

API Endpoint

An API endpoint is a specific URL:

An endpoint is a combination of the API's base URL and a specific path to the desired resource, along with the supported HTTP methods:

For example, the api/products/{id} endpoint that supports the following operations:

Endpoints often include query parameters, for example, GET /api/products?category=electronics&sort=price

OpenAPI Documentation

In the context of OpenAPI, the documentation describes the API as a whole, including all its endpoints and operations. OpenAPI provides a structured way to document APIs, making it easier for developers to understand how to interact with them.

API Operations are the primary focus of OpenAPI documentation. The OpenAPI specification organizes documentation by operations, which are grouped by paths (endpoints). Each operation is described with details such as parameters, request bodies, responses, and more. This structured format allows tools to generate client libraries, server stubs, and interactive documentation automatically.

In an OpenAPI document:

Example in OpenAPI JSON format:

json{
  "paths": {
    "/api/products/{id}": {  // This is the endpoint
      "get": {  // This is the operation
        "summary": "Get a product by ID",
        "parameters": [...],
        "responses": {...}
      },
      "put": {  // Another operation on the same endpoint
        "summary": "Update a product",
        "parameters": [...],
        "responses": {...}
      }
    }
  }
}

API, API operation, and API endpoint comparison

The following table summarizes the differences between an API, an API operation, and an API endpoint:

Concept API Operation API Endpoint
Definition A logical description of an API action: method + path + behavior The actual configured HTTP route that listens for requests
Level Conceptual, what action can happen Concrete, what URL and method are matched
Tied to OpenAPI API design/specification ASP.NET Core routing at runtime
Describes What the API does for example, "create product" Where and how to call it, for example, POST https://localhost:7099/api/products, POST https://contoso.com/api/products
In ASP.NET Core Controller actions or Minimal API methods, before routing resolves Endpoint objects resolved at runtime

ASP.NET Core OpenAPI source code on GitHub

Additional Resources