OpenAPI Document Generation in .NET 9 APIs

In this article, we will dig deep into Open API support introduced by Microsoft in .NET 9. This support makes it convenient for customers of applications to understand and write API calls accordingly and easily integrates with our automated HTTP client code generation tools such as Swagger.

What is Open API?

The OpenAPI specification is a widely accepted standard for defining HTTP APIs. It helps developers outline the structure of APIs, making it easier to integrate with tools like client and server generators, testing frameworks, documentation systems, and more. With .NET 9, ASP.NET Core now includes built-in support for generating OpenAPI documents for both controller-based and minimal APIs, thanks to Microsoft.AspNetCore.OpenApi package.

How to use it?

OpenAPI

This is an example of a basic ASP.NET Core 9 project demonstrating how to integrate OpenAPI support into the Program.cs. We already have the required setup available.

  • builder.Services.AddOpenApi();: This adds dependencies
  • app.MapOpenApi();: This registers an endpoint

Customizations

The below code updates the Open API documentation endpoint path. Always ensure that the path follows the convention as '<pathtodocument>.json'.

app.MapOpenApi("/openapidocument.json");

The below code updates the description of the document, marks the authorization header as required, and adds one additional server as part of the documentation.

builder.Services.AddOpenApi(options =>
{
    options.AddDocumentTransformer((document, context, cancellationToken) =>
    {
        document.Info.Description = "This is open api demo";

        // Add when authorization headers are required 
        var authComponent = new OpenApiComponents
        {
            Headers = new Dictionary<string, OpenApiHeader>
            {
                { "Authorization", new OpenApiHeader { Required = true } }
            }
        };
        document.Components = authComponent;

        // Add new server if app is available at multiple locations
        document.Servers.Add(new OpenApiServer
        {
            Url = "https://appdev.com/",
            Description = "This is dev server"
        });

        return Task.CompletedTask;
    });
});

Below is our final Open API JSON available at "https://localhost:7283/openapidocument.json".

{
  "openapi": "3.0.1",
  "info": {
    "title": "OpenAPIDemo | v1",
    "description": "This is open api demo",
    "version": "1.0.0"
  },
  "servers": [
    {
      "url": "https://localhost:7283"
    },
    {
      "url": "http://localhost:5196"
    },
    {
      "url": "https://appdev.com/",
      "description": "This is dev server"
    }
  ],
  "paths": {
    "/WeatherForecast": {
      "get": {
        "tags": [
          "WeatherForecast"
        ],
        "operationId": "GetWeatherForecast",
        "responses": {
          "200": {
            "description": "OK",
            "content": {
              "text/plain": {
                "schema": {
                  "type": "array",
                  "items": {
                    "$ref": "#/components/schemas/WeatherForecast"
                  }
                }
              },
              "application/json": {
                "schema": {
                  "type": "array",
                  "items": {
                    "$ref": "#/components/schemas/WeatherForecast"
                  }
                }
              },
              "text/json": {
                "schema": {
                  "type": "array",
                  "items": {
                    "$ref": "#/components/schemas/WeatherForecast"
                  }
                }
              }
            }
          }
        }
      }
    }
  },
  "components": {
    "schemas": {
      "WeatherForecast": {
        "type": "object",
        "properties": {
          "date": {
            "type": "string",
            "format": "date"
          },
          "temperatureC": {
            "type": "integer",
            "format": "int32"
          },
          "temperatureF": {
            "type": "integer",
            "format": "int32"
          },
          "summary": {
            "type": "string",
            "nullable": true
          }
        }
      }
    },
    "headers": {
      "Authorization": {
        "required": true
      }
    }
  },
  "tags": [
    {
      "name": "WeatherForecast"
    }
  ]
}

Now, you can simply add swagger UI using NSwag.AspNetCore package or any other package that uses Open API specifications.

In the case of NSwag.AspNetCore, you need to add the code below.

app.UseSwaggerUi(config =>
{
    config.DocumentPath = "/openapidocument.json";
});

Most of the things work fine as expected when you try Swagger UI. Additional configurations or adjustments may be required to ensure all the configurations are working as expected.

Below is a reference screenshot. You may notice that all the things mentioned above are visible, including the server name and description, etc.

Server name

I hope this was helpful. Do share your ideas in the comments to use this package better.


Similar Articles