Using Swagger to Document your API in .Net Core 3.1

Swagger, a service you can inject into the middleware pipeline, automatically creates web pages that document your API and allow you to exercise its public elements.

To add it to your API, do the following:

1. Download and Install the Swagger Library

To do this, open the Package Manager Console in Visual Studio (with your API project loaded) and execute :

Install-Package Swashbuckle.AspNetCore -Version 5.0.0

2. Add the SwaggerDoc Service to the DI Container

Add the following code to your DI container in Startup.cs’s ConfigureServices.

services.AddSwaggerGen(x =>
{
    x.SwaggerDoc("v1", new OpenApiInfo { Title = "IT Projects API", Version = "v1" });
});

OpenApiInfo is in Microsoft.OpenApi.Models so add a using expression to the top of Start.cs.

using Microsoft.OpenApi.Models;

3. Add Swagger to the Middleware Pipeline

app.UseSwagger();
app.UseSwaggerUI(c =>
{
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});

Note that “My API V1” will appear in the SwaggerUI web page.

4. Run Your API and Test the Swagger.json File

Swagger works by creating a JSON file that SwaggerUI uses to display information about your API. SwaggerUI creates this JSON file, swagger.json, by invoking

http://localhost:<port>/swagger/v1/swagger.json  

This should return a screenful of JSON data that describes your API. Of course replace <port> with the port your API is using.

5. Display the Swagger UI

Finally, to display the Swagger web interface, invoke:

http://localhost:<port>/swagger

Here’s a recent post that explains the above process in more detail: https://docs.microsoft.com/en-us/aspnet/core/tutorials/getting-started-with-swashbuckle?view=aspnetcore-3.1&tabs=visual-studio

You may also like...