Creating interactive documentation for a RESTful API with ASP.NET Core and Swagger

As intuitive as an API might seem to be in the minds of it's creators, consumers tend to have a different opinion.  This where good documentation which facilitates discovery comes into it's own.  Swagger and Swashbuckle makes this significantly easier.

Swagger describes, consumes and visualises RESTful APIs.  It makes sure the documentation and code stay in sync.

Swashbuckle significantly simplifies adding Swagger to a WebApi project.  It has no dependencies and comes with swagger-ui built-in.

Step 1: Create your project and install SwashBuckle from NuGet

In the package manager console:
PM> Install-Package Swashbuckle.AspNetCore

Step 2: Generate documentation from the XML comments in code

Use standard XML comments to document the Controllers and Entities that are exposed by the controller interfaces.  As long as the comments are of a sufficiently high standard, this leads to a "self-documenting" API.

In Visual Studio go to Project Properties > Build > Output, check 'Xml documentation file'

Step 3: Configure the Swagger documentation

In Startup.cs
a. Add using Swashbuckle.AspNetCore.Swagger;
b. In Startup.cs > ConfigureServices() add
services.AddSwaggerGen(c =>
c.SwaggerDoc("v1", new Info { Title = "Your API Name", Version = "v1" });
c.IncludeXmlComments(string.Format(@"{0}\YourProjectName.xml", System.AppDomain.CurrentDomain.BaseDirectory)); 

Step 4: Enable the Swagger UI

In Startup.cs > Configure() add
app.UseSwagger(); // generates the swagger.json file
app.UseSwaggerUI(c => 
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "Your API Name V1");
    }); // shows swagger ui

Step 5: Review the generated documentation

In Visual Studio go to Project Properties > Debug, set the 'Launch URL' to "swagger".

Start the service (with, or without, debugging).  And you get something like this: