We have been using Swashbuckle to auto-generate documentation for our .Net Core WebApi's. ASP .NET Core 5 supports the OpenAPI specification and the Web API project template enables the OpenAPI support by default, and includes a reference to the Swashbuckle.AspNetCore Nuget package.
Extending the Api Information
Out of the box you get a simple ui that has been generated by Swashbuckle introspecting over the controllers in the application. In Startup.cs the code provided by the project template includes just a title and a version number :
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "Weather Forecast API", Version = "v1" });
});
More information, such as Contact details, terms of service and license, can be provided to the UI by including further details to the OpenApiInfo object:
c.SwaggerDoc("v1", new OpenApiInfo
{
Version = "v1",
Title = "Weather Forecast API",
Description = "A simple ASP.NET Core Web API",
TermsOfService = new Uri("https://example.com/terms"),
Contact = new OpenApiContact
{
Name = "Contact Name",
Email = string.Empty,
Url = new Uri("https://localhost"),
},
License = new OpenApiLicense
{
Name = "Use under LICX",
Url = new Uri("https://localhost/license"),
}
});
Enumerations
By default enums are just listed by the index value, so in this example days of the week are list from 1 to 7:
It is possible to show the enums' string names using System.Text.Json. By adding Json Options when adding the controllers the enums will be displayed as strings.
services.AddControllers()
.AddJsonOptions(options =>
options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()));
It is also possible to do this if you are using NewtonSoft but you will also have to install the Swashbuckle.AspNetCore.Newtonsoft nuget package:
services
.AddControllers()
.AddNewtonsoftJson(options =>
options.SerializerSettings.Converters.Add(new StringEnumConverter()));
// the order is important this must cam after adding the controllers
services.AddSwaggerGenNewtonsoftSupport();
Using XML Comments
XML comments can be use to provide more information about the api endpoints to the document. Turn on XML documentation in the Build tab of the project properties page. Unfortunately turning on XML documentation means the warning CS1591: Missing XML comment for publicly visible type or member... will be raised, so to avoid these warnings also add code 1591 to the list of Suppress warnings:
The generated XML comments are included in the document by adding the path the generated xml file to the Swagger configuration:
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo
{
Version = "v1",
Title = "Weather Forecast API",
// code removed...
});
// Set the comments path for the Swagger JSON and UI.
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
c.IncludeXmlComments(xmlPath);
});
Now it is a question of just adding summary information to the Api endpoint:
/// <summary>
/// Get the weather forecast for day
/// </summary>
/// <param name="day"></param>
/// <response code="200">The weather forecast for the day</response>
[HttpGet("day")]
[ProducesResponseType(StatusCodes.Status200OK)]
public WeatherForecast ForDay(DayOfWeek day)
{
var rng = new Random();
return new WeatherForecast
{
Date = GetNextWeekday(DateTime.Now, day),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
};
}
These comments will be included in the UI document:
Default Media Type
A response media type is not set by default and the UI allows you to choose between: text/plain; application/json; and text/json. Generally our api's always return json so to set this as the default a ProducesAttribute needs to be added to the Controller or Method:
[Produces("application/json")]
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
// code removed...
}
The response media type in the document will now defult to appliation/json:
I hope you find this post useful, the source code can be found here in github