ASP.NET Core Web API Documentation with Swagger

ASPNET Core web API documentation with Swagger

This blog is going to explain how to implement Swagger documentation in ASP.NET Core. Swagger helps to describe API documents so that consumers can easily understand the API. Swagger UI offers a web-based UI. For the developer, this supports creating quick documentation. All public action methods can be tested using the Swagger UI.

Step 1:
First, you need to create an API project. New Project -> ASP.NET Core web application -> Provide Project Name-> Click Create button-> Select API -> Click Create Button. After that Create a API controller Empty.

Step 2:
The next step is to install the Swashbuckle package from the Nuget package. If you are using the NuGet UI, search for Swashbuckle.AspNetCore and install it. Otherwise, use the command below if you are using the Package Manager console.

Install-Package Swashbuckle.AspNetCore

Step 3:
The following is a Movie Model. I have added a summary on top of each property to describe the property

Movie.cs
public class Movie
{
    /// <summary>
    /// Name of the movie
    /// </summary>
    public string MovieName { get; set; }
    /// <summary>
    /// The year the movie was released
    /// </summary>
    public int ReleasedYear { get; set; }
    /// <summary>
    /// Co-Production Company name
    /// </summary>
    public string CoProduction { get; set; }
}

Step 4:
This step is a control class. In the sample controller, I added a Get method to display a list of movie details. For example, I added some direct movie values. Also, I have included summaries above the controller and Get method to describe the purpose of the controller and Get method.

SampleController.cs
/// <summary>
/// A sample controller to show the demo to Swagger
/// </summary>
[Route("api/[controller]")]
[ApiController]
public class SampleController : ControllerBase
{
    /// <summary>
    /// To return a list of movie  names
    /// </summary>
    /// <returns>List of movies</returns>
    [HttpGet]
    public List<Movie> Get()
    {
        List<Movie> listOfMovies = new List<Movie>() { 
            new Movie {MovieName = "The Good Dinosaur", ReleasedYear = 2015, CoProduction = "Pixar Animation Studios" },
            new Movie {MovieName = "Moana", ReleasedYear = 2016, CoProduction = "Walt Disney Animation Studios" },
            new Movie {MovieName = "Frozen II", ReleasedYear = 2019, CoProduction = "Walt Disney Animation Studios" }
        };
        return listOfMovies;
    }
}

Step 5:
This step is a Startup class. I have registered the Swagger Generator inConfigureServices method. It generates Swagger documentation directly from routes, controllers and models. It is integrated with Swagger endpoint middleware to automatically display Swagger JSON.

Next, I added the IncludeXmlComments method. It helps to show developer-friendly information. That is, it helps to display summary content

Startup.cs
public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();

    services.AddSwaggerGen(options =>
    {
        options.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo
        {
            Title = "Swagger Sample",
            Description = "ASP.NET Core web API documentation with Swagger",
            Version = "v1"
        });

        // To show the descrption
        string fileName = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
        string filePath = Path.Combine(AppContext.BaseDirectory, fileName);
        options.IncludeXmlComments(filePath);
    });
}

Next is a Configure method. I have added middleware to generate the JSON documentation.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
   ...
   ...
    ...

    // Enable middleware to deliver the generated swagger as a JSON endpoint.
    app.UseSwagger();
    app.UseSwaggerUI(c => { c.SwaggerEndpoint("v1/swagger.json", "Swagger Sample"); });
}

Step 6:
In the .csproj project file I added the GenerateDocumentationFile tag to the PropertyGroup. This will create an XML document file inside the bin folder. The XML file name is the same as the project file name.

SampleAPI.csproj
<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
    <GenerateDocumentationFile>true</GenerateDocumentationFile>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Swashbuckle.AspNetCore" Version="5.6.3" />
  </ItemGroup>
</Project>

Output
To launch the application, type the following address in the browser address bar http://localhost:<port>/swagger. It will provide Swagger UI.

The image below is the output of the code above. It shows how the document is created. When the user clicks the Try it out -> Execute button it shows the code and JSON response.

ASP.NET Core web API documentation with Swagger

I hope this helps you. Keep coding.

Comments

Popular posts from this blog

Entity Framework Core (EF) with SQL Server LocalDB

SignalR with JavaScript in ASP.NET Core MVC

Localization in ASP.NET Core MVC with Example