Kirkbride Solutions

How To: Add Swashbuckle/Swagger to a .Net Core API

C#tutorial

Good API documentation is very important to having a reliable and supportable API. In order to accomplish this in my little demo Conferences.Api on GitHub here, I'll be using Swashbuckle to auto generate a Swagger document that will grow as the API does.

Let's get started with Swashbuckle and Swagger! Swagger is pretty much an industry standard now for documenting APIs. Because of its popularity and usefulness there are a lot of ways to get auto-generated documents and even test clients now.

Swashbuckle is a pretty common swagger generation NuGet package. It is easy to integrate into a .Net Core Api. Head over to NuGet and install the package Swashbuckle.AspNetCore.

The Swashbuckle documentation is pretty good and you can find it on their GitHub page here. I'll be using version 4 for the Conferences.Api. However, 5 is currently in release candidate. Following along with the documentation we need to add some code to the ConfigureServices method in the Startup.cs file:

services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info { Title = "Conferences Api", Version = "v1" });
});

You will need to import using Swashbuckle.AspNetCore.Swagger

Also on the Configure method you will need to add:

app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "Conference Api v1");
});

We'll expand this a bit once we get into things like security. However, for now this should suffice. We can run the application and navigate to /swagger. I will also note it's probably a good idea to have the app.UserSwaggerUI above your app.UseMvc. If you're using any of the Spa related code in Startup it may overwrite your /swagger route with your catch all route. So it's just safer to go ahead and put it ahead of the app.UseMvc.

Conferences API Swagger screenshot

You should see something like that. By clicking on the Get route we can actually execute a test call against our API.

You can hit the "Exceute" button and get a response back like this:

Conferences Endpoint Swagger screenshot

We can also provide a topic as a query string parameter and verify that works as well.

Conferences Endpoint Swagger screenshot

Commit Swagger added