ASP.NET – Use Swagger to generate API documentation

The simplest way to add API documentation is to use Swagger. You can configure it to generate an API documentation page and even send requests to your endpoints. Here’s what it looks like:

Swagger API documentation - shows your API endpoints, including the objects passed into the request, XML comments, and required fields

In this article I’ll show how to install and configure Swagger with the following features (shown in the image above):

  • Generates an API documentation page.
  • Displays XML comments for the controller and objects used in the request (the schema).
  • Shows required fields.

1 – Install the Swagger ASP.NET nuget package

  • Search for Swashbuckle.AspNetCore package
  • Install it
In Nuget Package Manager, search for Swashbuckle.AspNetCore and click Install

This installs the three packages you need:

  • Swashbuckle.AspNetCore.Swagger
  • Swashbuckle.AspNetCore.SwaggerGen
  • Swashbuckle.AspNetCore.SwaggerUI

2 – Add Swagger service and middleware in Startup

Add Swagger in ConfigureServices(…) and Configure(…). See the highlighted lines in the code below.

using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using System; using System.IO; namespace SimpleSwagger { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services) { //1 - Add Swagger service and include XML documentation services.AddSwaggerGen(c => { var filePath = Path.Combine(AppContext.BaseDirectory, "SimpleSwagger.xml"); c.IncludeXmlComments(filePath, includeControllerXmlComments: true); }); services.AddControllers(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } //2 - Enable Swagger middleware app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API v1"); }); app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } } }
Code language: C# (cs)

3 – Configure it to launch the Swagger API doc page

In /Properties/launchSettings.json, set the launchUrl to “swagger.”

{ "$schema": "", "iisSettings": { "windowsAuthentication": false, "anonymousAuthentication": true, "iisExpress": { "applicationUrl": "http://localhost:39257", "sslPort": 44379 } }, "profiles": { "IIS Express": { "commandName": "IISExpress", "launchBrowser": true, "launchUrl": "swagger", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } }, "SimpleSwagger": { "commandName": "Project", "launchBrowser": true, "launchUrl": "swagger", "applicationUrl": "https://localhost:5001;http://localhost:5000", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } } } }
Code language: JSON / JSON with Comments (json)

4 – Automatically generate XML documentation from XML comments

To get Swagger to show XML comments you have to make your project output an XML documentation file.

In the project Build properties, put on a check on XML documentation file.

Visual Studio project build properties - putting a check on the XML documentation file option

5 – Add XML comments and the [Required] attribute

Here is the StockMarketController and Stock class. I put XML comments – ///<summary> on properties and methods, and used the [Required] attribute in the Stock class. Swagger will show these XML comments and show which fields are required.

using Microsoft.AspNetCore.Mvc; using System.ComponentModel.DataAnnotations; namespace SimpleSwagger.Controllers { [ApiController] [Route("stocks")] public class StockMarketController : ControllerBase { /// <summary> /// Updates information for a stock in the system /// </summary> /// <param name="stock"></param> /// <returns></returns> [HttpPost] public IActionResult UpdateStock([FromBody]Stock stock) { //update the stock data in the system return Ok(); } } /// <summary> /// Test /// </summary> public class Stock { /// <summary> /// Unique identifier of stock /// Ex: VTSAX (Vanguard Total Stock Market Index Fund) /// </summary> [Required] public string TickerSymbol { get; set; } /// <summary> /// The current price of the stock /// Ex: 82.20 /// </summary> [Required] public decimal Price { get; set; } } }
Code language: C# (cs)

6 – Start your web API and send a request via Swagger’s [Try it out]

  • Start your project (Start without debugging – Ctrl+F5). This will launch the Swagger doc page in the browser.
  • Click Try it out
Swagger API doc - clicking Try it out to send a request to your endpoint
  • Fill out the request body JSON, then click Execute.
Swagger API doc page - sending a request to your endpoint
  • Look at the response.
Swagger API Doc page showing the response of sending a request to your API

Leave a Comment