Web API Documentation Using Swagger And ASP.NET Core With Visual Studio 2019

Introduction

 
There are many challenges we face for consuming a Web API because it contains various methods such as - GET, POST, PUT, DELETE. All these methods contain various types of parameters like model, string, int, etc. We don’t know what exact properties we need to pass in the model parameter and what are the relevant ones. These are the major challenges for a developer and so we need proper documentation to solve this problem. That’s why we choose Swagger, also known as OpenAPI. It provides all such benefits like interactive documentation, client SDK generation, and API discoverability. In this article, I am explaining a few basic configurations of Swagger in ASP.NET Core applications. We can add more additional features on the Web API using Swagger. For that, just read the reference document that I have mentioned in the Reference section.
 
Before reading this article, you must read the articles given below for ASP.NET Core knowledge.
We have tested the Swagger documentation application in the latest VS 2019. So, please check the following steps to kickstart the initial process of installation.
 
Open Visual Studio 2019 and click on "Create a new project".
 
Web API Documentation Using Swagger And ASP.NET Core With Visual Studio 2019
 
Click on ASP.NET Core Web Application.
 
Web API Documentation Using Swagger And ASP.NET Core With Visual Studio 2019
 
Provision your new project and give the appropriate name and the location to be saved.
 
Web API Documentation Using Swagger And ASP.NET Core With Visual Studio 2019
 
Choose API and click on the "Create" button on the right side.
 
Web API Documentation Using Swagger And ASP.NET Core With Visual Studio 2019
 
Open "Tools -> NuGet Package Manager -> Manage NuGet Packages for Solution…" and click the Browse tab. Search for "Swashbuckle.AspNetCore" in the search bar and install it.
 
Web API Documentation Using Swagger And ASP.NET Core With Visual Studio 2019
 

Model

 
We are going to create an Employee model for demo purposes.
  1. namespace SwaggerDocumentation.Model  
  2. {  
  3.     public class Employee  
  4.     {  
  5.   
  6.         /// <summary>  
  7.         /// Employee id  
  8.         /// </summary>  
  9.         public int id { getset; }  
  10.   
  11.         /// <summary>  
  12.         /// Name of the employee.  
  13.         /// </summary>  
  14.         public string Name { getset; }  
  15.   
  16.         /// <summary>  
  17.         /// Employee personal address.  
  18.         /// </summary>  
  19.         public string Adress { getset; }  
  20.   
  21.         /// <summary>  
  22.         /// Department unit of the employee.  
  23.         /// </summary>  
  24.         public string Department { getset; }  
  25.   
  26.     }  
  27. }  

API Version Separation

 
In future, if we are planning to release multiple versions of an API, then, for better readability  we can create a version folder for the API creation. This will help us to differentiate multiple versions in the API side and Swagger documentation. In the following screenshot, we have created two folders - one is "v1" ( Version 1 ) and another one is "v2" ( Version 2 ). Obviously, v2 will contain the latest version comparing to v1.
 
Web API Documentation Using Swagger And ASP.NET Core With Visual Studio 2019

 
API Controller

 
We have created "EmployeeController" as the API controller in our application. Here we can see at the route level the API path is set as "api/v1/[controller]" because when you hit Swagger it will first check the controller level then it will take two identical controller names as “Employee”. This will create an ambiguous issue in the HTTP request controller level, for that reason we have added two different request paths for both versions, v1 & v2.
  1. using System.Collections.Generic;  
  2. using Microsoft.AspNetCore.Mvc;  
  3. using SwaggerDocumentation.Model;  
  4.    
  5. namespace SwaggerDocumentation.Controllers.v1  
  6. {  
  7.     [Route("api/v1/[controller]")]  
  8.     [ApiController]  
  9.     public class EmployeeController : ControllerBase  
  10.     {  
  11.         // GET: api/v1/Employee  
  12.         [HttpGet]  
  13.         public List<Employee> EmployeesDetails()  
  14.         {  
  15.             List<Employee> employees = new List<Employee>  
  16.             {  
  17.                new Employee  
  18.                {  
  19.                    Name = "Rajeesh",  
  20.                    Department = "Development",  
  21.                    Adress = "Menoth Parambil"  
  22.                },  
  23.    
  24.                new Employee  
  25.                {  
  26.                    Name = "Arokia",  
  27.                    Department = "R/D",  
  28.                    Adress = "Trichy Central"  
  29.                },  
  30.    
  31.                new Employee  
  32.                {  
  33.                    Name = "Vijay",  
  34.                    Department = "Cloud",  
  35.                    Adress = "MP Gowliyar"  
  36.                },  
  37.    
  38.             };  
  39.    
  40.             return employees;  
  41.         }  
  42.    
  43.         // GET: api/v1/Employee/5  
  44.         [HttpGet("{id}", Name = "Get")]  
  45.         public Employee EmployeeDetailsInformation(int id)  
  46.         {  
  47.             List<Employee> employees = new List<Employee>  
  48.             {  
  49.                new Employee  
  50.                {  
  51.                    id = 1,  
  52.                    Name = "Rajeesh",  
  53.                    Department = "Development",  
  54.                    Adress = "Menoth Parambil"  
  55.                },  
  56.    
  57.                new Employee  
  58.                {  
  59.                    id = 2,  
  60.                    Name = "Arokia",  
  61.                    Department = "R/D",  
  62.                    Adress = "Trichy Central"  
  63.                },  
  64.    
  65.                new Employee  
  66.                {  
  67.                    id = 3,  
  68.                    Name = "Vijay",  
  69.                    Department = "Cloud",  
  70.                    Adress = "MP Gowliyar"  
  71.                },  
  72.    
  73.             };  
  74.    
  75.             return employees.Find(x => x.id == id);  
  76.         }  
  77.    
  78.         // POST: api/v1/Employee  
  79.         [HttpPost]  
  80.         [ApiExplorerSettings(GroupName = "v1")]  
  81.         public void Post([FromBody] string value)  
  82.         {  
  83.         }  
  84.    
  85.         // PUT: api/v1/Employee/5  
  86.         [HttpPut("{id}")]  
  87.         public void Put(int id, [FromBody] string value)  
  88.         {  
  89.         }  
  90.    
  91.         // DELETE: api/v1/ApiWithActions/5  
  92.         [HttpDelete("{id}")]  
  93.         public void Delete(int id)  
  94.         {  
  95.         }  
  96.     }  
  97. }  

IControllerModelConvention

 
In the ASP.NET Core MVC, we have application model and it will define convention abstractions that provide a simpler way to customize the behavior of the models without overriding the entire model. In a simpler way, we are modifying our app to follow different conventions from the default MVC behavior. The following method is clearly describing that it will take the last name of the "namespace" and it considers it as the group name of the API Version. So, in this case, we can easily separate out versions when we maintain multiple versions of APIs in the application. The "GroupName" can be declared as globally and locally, but in multiple API version cases, we can go with the global scenario.
  1. public class ApiExplorerVersionConvention : IControllerModelConvention  
  2.     {  
  3.         public void Apply(ControllerModel controller)  
  4.         {  
  5.             var controllerNamespace = controller.ControllerType.Namespace; // e.g. "Controllers.v1"  
  6.             var apiVersion = controllerNamespace.Split('.').Last().ToLower();  
  7.    
  8.             controller.ApiExplorer.GroupName = apiVersion;  
  9.         }  
  10.     }  
We can declare group name locally in the following way, but in this scenario you need to add the following decorator for each API method.
  1. // POST: api/v1/Employee  
  2.        [HttpPost]  
  3.        [ApiExplorerSettings(GroupName = "v1")]  
  4.        public void Post([FromBody] string value)  
  5.        {  
  6.        }  

Middleware

 
We need to inject swagger service in the ASP.NET Core application using the middleware in startup class. Then only can we access the entire swagger service in our application.
 

ConfigureServices ( Inside the Startup.cs )

 
ConfigureServices method gets called by the runtime so we can use this method to register the services to the container in the application. First of all, we need to add "ApiExplorerVersionConvention" convention in the MVC service like the following way.
  1. services.AddMvc(x => x.Conventions.Add(new ApiExplorerVersionConvention()));  
The following code will register the swagger in our Application. There are many properties we use in the following code like "v1" & "v2" consider as GroupName, Title is displayed as "Swagger Documentation" and "Version 1.0" & "Version 2.0" is the version separation.
 

Configure ( Inside the Startup.cs )

 
Configure method gets called by the runtime and we use this method to configure the HTTP request pipeline. We are going to enable the generated Swagger as a JSON endpoint in the middleware and it will serve to the request.
  1. app.UseSwagger();  
We can mention the swagger UI and JSON endpoint in the following way.
  1. app.UseSwaggerUI(c =>  
  2.             {  
  3.                 c.SwaggerEndpoint("/swagger/v1/swagger.json""My API V1");  
  4.                 c.SwaggerEndpoint("/swagger/v2/swagger.json""My API V2");  
  5.             });  

launchSettings.json

 
In launchSettings.json we can setup swagger as the launch URL. This is not mandatory to give because for the demo we have given the launch URL as swagger. Otherwise, in middleware, we have SwaggerEndpoint "/swagger/v1/swagger.json" so you can enter in the browser like "http://localhost:44392/api/swagger".
  1. {  
  2.   "$schema""http://json.schemastore.org/launchsettings.json",  
  3.   "iisSettings": {  
  4.     "windowsAuthentication"false,   
  5.     "anonymousAuthentication"true,   
  6.     "iisExpress": {  
  7.       "applicationUrl""http://localhost:62460",  
  8.       "sslPort": 44392  
  9.     }  
  10.   },  
  11.   "profiles": {  
  12.     "IIS Express": {  
  13.       "commandName""IISExpress",  
  14.       "launchBrowser"true,  
  15.       "launchUrl""swagger",  
  16.       "environmentVariables": {  
  17.         "ASPNETCORE_ENVIRONMENT""Development"  
  18.       }  
  19.     },  
  20.     "SwaggerDocumentation": {  
  21.       "commandName""Project",  
  22.       "launchBrowser"true,  
  23.       "launchUrl""api/values",  
  24.       "applicationUrl""https://localhost:5001;http://localhost:5000",  
  25.       "environmentVariables": {  
  26.         "ASPNETCORE_ENVIRONMENT""Development"  
  27.       }  
  28.     }  
  29.   }  
  30. }  

Output

 
Web API Documentation Using Swagger And ASP.NET Core With Visual Studio 2019
 
Reference

Summary

 
From this article, we have learned the Web API documentation using Swagger & ASP.NET Core With Visual Studio 2019. I hope this article is useful for all the ASP.NET Web API beginners.