Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / .NET / .NET-Core

Documenting an ASP.NET Core API with OpenAPI / Swagger

3.00/5 (3 votes)
10 Jul 2020MIT3 min read 11.3K  
How to document ASP.NET Core API using OpenAPI / Swagger
Documentation is always a tedious, but essential task. By using OpenAPI / Swagger, which integrates nicely with ASP.NET Core, you can take on this task.

Table of Contents

  1. What is Swagger/ OpenAPI and Why Use it to Document your API
  2. Getting Started
  3. Introduction of ASP.NET Core API Demo
  4. Using the Code
    1. Installing the Swashbuckle.AspNetCore Package and Registering
    2. Adding Swagger UI
    3. Including XML Documentation on Action and Classes
    4. To Ignore XML Warning
    5. Adding API Information and Details
    6. Working with Multiple OpenAPI
  5. Conclusion
  6. References
  7. History

What is Swagger/ OpenAPI and Why Use it to Document Your API

Swagger is an open-source software framework backed by a large ecosystem of tools that helps developers design, build, document, and consume RESTful web services. While most users identify Swagger by the Swagger UI tool, the Swagger toolset includes support for automated documentation, code generation, and test-case generation.

Imagine in your company if your colleague Front end developer or other team using your API in same company, where you have to spend your time answering the same question, how to integrate with this API and specification. Through Swagger or OpenAPI, you can solve your problem.

OpenAPI Specification, originally known as the Swagger Specification. Both terms are interchangeable, but OpenAPI is the preferred term. Once you start surfing around for information on OpenAPI or Swagger, you will quickly encounter terms like Swagger UI, Swashbuckle, NSwag, and so on.

Swagger is a set of open source tools built around that OpenAPI specification.

Swashbuckle.AspNetCore helps with working with OpenAPI in ASP.NET Core.

Image 1

Getting Started

For this tutorial, I will work on an ASP.NET Core 3.1 API to demonstrate the features of the Swagger. I use Visual Studio 2019 Community as my IDE.

Introduction of ASP.NET Core API Demo

We are going to build Swagger on top of this API application, where it contains simple CRUD operation with Entity Framework Core using InMemory provider Sample Startup Project.

Using the Code

Installing the Swashbuckle.AspNetCore Package and Registering

Add the below nuget library SwaggerDemo:

  • Swashbuckle.AspNetCore

Register swagger in ConfigureServices and Configure methods in Startup.cs file:

C#
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using SwaggerDemo.Data;

namespace SwaggerDemo
{
    public class Startup
    {
        // ...

        public void ConfigureServices(IServiceCollection services)
        {
           // ...

            services.AddSwaggerGen(setupAction =>
            {
                setupAction.SwaggerDoc(
                    "OpenAPISpecification",
                    new Microsoft.OpenApi.Models.OpenApiInfo()
                    {
                        Title = "Customer API",
                        Version = "1"
                    });
            });
        }

        // This method gets called by the runtime. 
        // Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            // ...

            app.UseRouting();

            app.UseSwagger();

            //...
        }
    }
} 

Once it is registered, open the below URL and check that it is working:

http://localhost:53456/swagger/OpenAPISpecification/swagger.json

Adding Swagger UI

Register swagger UI in Configure methods in Startup.cs file as shown below:

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

    app.UseSwagger();

    app.UseSwaggerUI(setupAction =>
       {
           setupAction.SwaggerEndpoint
           ("/swagger/OpenAPISpecification/swagger.json", "Customer API");
           setupAction.RoutePrefix = ""; // To available at root
       });

  //...
}

Once it is registered, open the below URL and check in below URL:

http://localhost:53456/index.html

Including XML Documentation on Action and Classes

Go to property of project and add XML document as shown below:

Image 2

Incorporate this XML in ConfigureServices:

C#
public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();

    services.AddDbContext<customercontext>(opt =>
         opt.UseInMemoryDatabase("InMemoryCustomerDB")
      );

    services.AddSwaggerGen(setupAction =>
    {
       // ...

        var xmlCommentsFile =
            $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
        var xmlCommentsFullPath =
            Path.Combine(AppContext.BaseDirectory, xmlCommentsFile);
        setupAction.IncludeXmlComments(xmlCommentsFullPath);
    });
}

Add summary comment as shown below:

C#
/// <summary>
/// Get customer detail by id
/// </summary>

///<param name="id" />This id is unique/primary key of customer
/// <returns>Customer details with id,
/// customername and cutomer code fields
[HttpGet]
[Route("{id}", Name = "GetCustomer")] public ActionResult<customer> Get(int id) {
//... }

Summary will look as shown below:

Image 3

To Ignore XML Warning

Go to property of project and suppress XML warning (i.e., 1591) as shown below:

Image 4

Adding API Information and Details

Add the below information details if required:

C#
services.AddSwaggerGen(setupAction =>
{
    setupAction.SwaggerDoc(
        "OpenAPISpecification",
        new Microsoft.OpenApi.Models.OpenApiInfo()
        {
            Title = "Customer API",
            Version = "1",
            Description ="Through this API you can access customer details",
            Contact = new Microsoft.OpenApi.Models.OpenApiContact()
            {
                Email="amit.naik8103@gmail.com",
                Name ="Amit Naik",
                Url = new Uri("https://amitpnk.github.io/")
            },
            License = new Microsoft.OpenApi.Models.OpenApiLicense ()
            {
                Name ="MIT License",
                Url =new Uri("https://opensource.org/licenses/MIT")
            }
        });

    var xmlCommentsFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
    var xmlCommentsFullPath =
        Path.Combine(AppContext.BaseDirectory, xmlCommentsFile);
    setupAction.IncludeXmlComments(xmlCommentsFullPath);
});

API Explorer and Its Usage

ApiExplorer is an abstraction on top of ASP.NET Core MVC that exposes metadata about that application:

Will see how we can use it.

Add below nuget library SwaggerDemo:

  • Microsoft.AspNetCore.Mvc.Api.Analyzers

Register in Startup.cs file for global level:

C#
      public void ConfigureServices(IServiceCollection services)
      {
          services.AddMvc(setupAction =>
           {
               setupAction.Filters.Add(
                      new ProducesResponseTypeAttribute(StatusCodes.Status400BadRequest));
               setupAction.Filters.Add(
                      new ProducesResponseTypeAttribute(StatusCodes.Status406NotAcceptable));
               setupAction.Filters.Add(
                      new ProducesResponseTypeAttribute
                          (StatusCodes.Status500InternalServerError));
               setupAction.Filters.Add(
                      new ProducesDefaultResponseTypeAttribute());
           });
//...
      }

Working with Multiple OpenAPI

If your API module is increasing and now you need to make it group in ConfigureService and Configure method as shown in the following steps:

C#
services.AddSwaggerGen(setupAction =>
{
    setupAction.SwaggerDoc(
        "OpenAPISpecificationCustomer",
        new Microsoft.OpenApi.Models.OpenApiInfo()
        {
            Title = "Customer API",
            Version = "1",
            Description = "Through this API you can access customer details",
            Contact = new Microsoft.OpenApi.Models.OpenApiContact()
            {
                Email = "amit.naik8103@gmail.com",
                Name = "Amit Naik",
                Url = new Uri("https://amitpnk.github.io/")
            },
            License = new Microsoft.OpenApi.Models.OpenApiLicense()
            {
                Name = "MIT License",
                Url = new Uri("https://opensource.org/licenses/MIT")
            }
        });

    setupAction.SwaggerDoc(
      "OpenAPISpecificationWeatherDefault",
      new Microsoft.OpenApi.Models.OpenApiInfo()
      {
          Title = "Weather default API",
          Version = "1",
          Description = "Through this API you can access customer details",
          Contact = new Microsoft.OpenApi.Models.OpenApiContact()
          {
              Email = "amit.naik8103@gmail.com",
              Name = "Amit Naik",
              Url = new Uri("https://amitpnk.github.io/")
          },
          License = new Microsoft.OpenApi.Models.OpenApiLicense()
          {
              Name = "MIT License",
              Url = new Uri("https://opensource.org/licenses/MIT")
          }
      });
C#
app.UseSwaggerUI(setupAction =>
{
    setupAction.SwaggerEndpoint
    ("/swagger/OpenAPISpecificationCustomer/swagger.json", "Customer API");
    setupAction.SwaggerEndpoint
    ("/swagger/OpenAPISpecificationWeatherDefault/swagger.json", "Weather default API");

    setupAction.RoutePrefix = string.Empty;
});
C#
[Route("api/[controller]")]
[ApiExplorerSettings(GroupName = "OpenAPISpecificationCustomer")]
[ApiController]
public class CustomerController : ControllerBase
{
      // ...
}

References

History

  • 10th July, 2020: Initial version

License

This article, along with any associated source code and files, is licensed under The MIT License