Monday, May 27, 2024

.NET 9 and ASP.NET Core: Built-in Support for OpenAPI Document Generation

With .NET 9, ASP.NET Core now has built-in support for OpenAPI document generation in both controller-based and minimal APIs. For as long as I can remember, ASP.NET Core has been using Swagger to generate the Open API document. Now we have Microsoft.AspNetCore.OpenApi package, and technically we can get rid of using Swagger. The new package still doesn't support a rich UI like Swagger UI, and that's something to look forward to.

Now let's see how this works.

Install the package: Microsoft.AspNetCore.OpenApi, note: it has to be the latest preview as of today and that is 9.0.0-preview.4.24267.6 (or any newer version than this).
<Project Sdk="Microsoft.NET.Sdk.Web">

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

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="9.0.0-preview.4.24267.6" />
  </ItemGroup>

</Project>
Now we can create a simple API something like follows:
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);

builder.Services.AddOpenApi();

WebApplication app = builder.Build();

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

app.MapGet("/hello", () => "Hello world!")
    .WithDescription("Returns Hello");

app.Run();
You can access the OpenAPI document at: https://localhost:<port>/openapi/v1.json
OpenAPI Document
Read the following documentation to learn all the different customization options:

Hope this helps.

Happy Coding.

Regards,
Jaliya

No comments:

Post a Comment