Understand OpenAPI document generation in ASP.NET Core
If you are following the latest happenings in the ASP.NET space then you are probably aware that Swagger UI support has been removed from the default Web API project template. The default project template now simply provides support for generating OpenAPI documents. Of course, you can still use third party tools such as Swagger and Scalar to read the OpenAPI documents generated and to test the underlying Web API.
Although this change has been introduced in .NET 9, beginners might find it useful to understand how various pieces of the picture fit together for the new as well as the older versions of .NET. Therefore, in this article I am going to explain the basics of using OpenAPI, Swagger, and Scalar from the ground up. So, let's get started by creating a simple CRUD Web API using Visual Studio Code.
Make sure you have .NET 9 SDK installed on your machine. Then open VS Code and create a new Web API project named EmployeesApi.
Once the project is created, expand the dependencies to reveal this entry:
As you can see, there is an entry for NuGet package -- Microsoft.AspNetCore.OpenApi.
The OpenAPI specifications is a standard for describing HTTP based APIs. Using the OpenAPI standards you can document your Web APIs and Minimal APIs. The OpenAPI document can then be used by third party vendors to generate UI, client code, tests, and more.
The Microsoft.AspNetCore.OpenApi functionality is wired into your app in the Program.cs like this :
...
builder.Services.AddOpenApi();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.MapOpenApi();
}
...
The call to AddOpenApi() adds OpenAPI services and MapOpenApi() configures the endpoint for the resultant OpenAPI document. By default, the OpenAPI documents can be accessed at https://localhost:port/openapi/v1.json
Run the app and navigate to the /weatherforecast endpoint just to confirm that the template provided minimal API works as expected.
Now, navigate to the OpenAPI document by entering the URL mentioned earlier.
As you can see, you are served a JSON document that describes the API.
You can change the document name by specifying a desired one in the AddOpenApi() call.
builder.Services.AddOpenApi("MyOpenApiDoc");
We changed the document name from v1 to MyOpenApiDoc. If you try to navigate to the older URL, you will get an error:
Enter the new document URL -- https://localhost:port/openapi/MyOpenApiDoc.json -- and you will be served with the document as before.
You can also change the route / URL of the document by modifying the MapOpenApi() call like this :
app.MapOpenApi("/openapi/{documentName}
/document.json");
We have added openapi route segment and {documentName} route parameter to the URL. With this change, our new URL to access the document will be -- /openapi/MyOpenApiDoc/document.json
So far, we used the minimal API included in the default project template. We will also check the generation of OpenAPI document with a controller based API.
Add a new class to the project called WeatherController.cs. Write the following code in the WeatherController class.
[Route("api/[controller]")]
[ApiController]
public class WeatherController : ControllerBase
{
string[] summaries = new[]
{
"Freezing", "Bracing", "Chilly",
"Cool", "Mild", "Warm", "Balmy",
"Hot", "Sweltering", "Scorching"
};
[HttpGet]
public IActionResult Get()
{
var forecast = Enumerable.Range(1, 5)
.Select(index =>
new WeatherForecast
(
DateOnly.FromDateTime
(DateTime.Now.AddDays(index)),
Random.Shared.Next(-20, 55),
summaries[Random.Shared.Next
(summaries.Length)]
))
.ToArray();
return Ok(forecast);
}
}
It is the same code as in the /weatherforecast minimal API but now it is wrapped in a Get() action of the WeatherController class. The resultant API can be accessed at /api/weather.
Run the app again and navigate to the OpenAPI document. This time you will see the details of the newly added API as shown below:
Now that we have confirmed the working of the OpenAPI document, let's see how Swagger UI can be added to the project if required.
To use Swagger, first you need to install Swashbuckle.AspNetCore NuGet package. Right click on the project in the Solution Explorer and click on the Add NuGet Package menu option.
Then search for Swashbuckle.AspNetCore and install the latest version of the package.
Next, open Program.cs and add these calls :
if (app.Environment.IsDevelopment())
{
app.MapOpenApi("/openapi/{documentName}
/document.json");
app.UseSwaggerUI(o=> {
o.SwaggerEndpoint("/openapi/MyOpenApiDoc
/document.json",
"swagger");
});
}
As you can see, we added a call to UseSwaggerUI() and specified the endpoint URL. Note that we have changed our OpenAPI document URL in the preceding example and hence UseSwaggerUI() uses the modified URL. If you are using the default URL then you should specify that URL in the UseSwaggerUI() call.
Run the app and enter /swagger in the address bar to open the Swagger UI.
If you click on the OpenAPI document mentioned at the top you will see the same JSON document as before. You can test the minimal API and controller based API as you normally do in Swagger UI. I am not going to discuss that in this article.
Now, let's add Scalar into the project. To use Scalar you need to install Scalar.AspNetCore NuGet package.
Once installed, open Program.cs and add this code:
if (app.Environment.IsDevelopment())
{
app.MapOpenApi();
app.MapScalarApiReference();
}
We simply make a call to MapScalarApiReference(). Run the app again and navigate to /scalar/MyOpenApiDoc
As you can see, Scalar shows the details as found in the OpenAPI document. You can test the minimal API as well as controller based API as you normally do in Scalar.
In this article you learned about the OpenAPI support in .NET 9. You also added Swagger and Scalar to read the generated OpenAPI document. We haven't developed the Employees CRUD Web API as yet. We will do that in the upcoming parts of this article.
That's it for now! Keep coding!!