← Back to articles

ASP.NET Core API with Swagger UI

Part of my ASP.NET Core recipe series: exposing your API with Swagger UI so it documents and exercises itself.

Tedd

Swagger makes the API machine readable. This means documentation and client implementations can be produced automatically. Swashbuckle runs top of Swagger and provides an UI. Together they provide nice functionality for documenting and testing your API.

Install

Install-Package Swashbuckle.AspNetCore

Implement

In Startup.cs ConfigureServices:

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

In Configure:

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

RoutePrefix is required when API is located under /api/.

Note that Swagger is sensitive to errors in Controller, i.e. missing [HttpGet] or similar. You can get a hint of what is wrong by visiting /swagger/v1/swagger.json.

Test

Navigate to /api/-folder of website.

Written by Tedd · Oslo, Norway

Updated 25 Jun 2019

Follow the journal via RSS