Generate Help Pages for your ASP.NET Core Web Api using Swagger

For any Web API developers, documenting your API and its methods is of paramount importance. Because these are intended to be consumed third parties, they will find it hard to incorporate it without any proper documentation. Creating a document is a very tedious and time-consuming job and most of the developers are least worried about it. This is where tools like Swagger which can automatically generate the documentation for you by examining your API code. 

Adding Swagger

To set it up, you will need to add the below package to your project. This is can be done using the NuGet Package Manager in Visual Studio or by executing the following command in the Package Manager Console window

Install-Package Swashbuckle.AspNetCore

This package will add the following components

  1. Swashbuckle.AspNetCore.Swagger : Middleware used to expose Swagger Document as a JSON endpoint
  2. Swashbuckle.AspNetCore.SwaggerGen : a generator that builds the Swagger Document by looking into your controllers and action methods
  3. Swashbuckle.AspNetCore.SwaggerUI : interprets the JSON outputted by the endpoint and builds an interactive UI

Configuring Swagger in your API Project

Adding and configuring Swagger is done in the Program class, first, you will need to import the following namespace

using Microsoft.OpenApi.Models;

Then in the ConfigureServices method, register the Swagger generator and define a document

services.AddSwaggerGen(c =>
 {
     c.SwaggerDoc("v1", new OpenApiInfo { Title = "Swagger Sample API V1", Version = "v1" });
 });

In the Configure method, add the two statements given below. The first one will enable the middleware to serve the generated document and the second one this document to show the interactive UI

//enables middleware
app.UseSwagger();

//enables SwaggerUI middleware to serve the UI for documentation
//and also specified the Swagger JSON endpoint
app.UseSwaggerUI(c =>
{
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "Swagger Sample API V1");
});

Here's the Configure method in full

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseSwagger();

    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "Swagger Sample API V1");
    });


    app.UseHttpsRedirection();

    app.UseRouting();

    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}

Accessing Swagger UI

You can access the UI by appending "swagger" to the root URL. For example, if you run the project just created, the interactive documentation will look like the one given below


No Comments

Add a Comment