Document Your Existing API's With (Open API) Specification in ASP.NET Core

Introduction

 
In this article, we will learn how to document our already existing APIs with .Net and.Net Core. Many developers absolutely deplore writing documentation. It's boring to put all these things together in a document by manually writing them. To overcome this we have Swagger to implement documentation and it's an open-source API documentation tool.
 
Packages required to configure Swagger,
  1. Swashbuckle.AspNetCore (latest version) - This package adds Swagger and Swagger UI and other libraries to make it easy for us to create API documentation. 
Step 1
 
After installing the package to the respective project, here I am sharing the screenshot for your reference if you are  new to Swagger in ASP.Net Core
 
 
Step 2 - Setup
 
We need to enable our project to generate XML comments. The comments come from Triple-slash (///) comments throughout the code. 
 
First, in the project properties, check the box labeled "Generate XML Documentation" 
 
Right Click on the Solution and click on the Properties
 
 
You will probably also want to suppress warning 1591, which will now give warnings about any method, class, or field that doesn't have triple-slash comments.
 
 
Step 3 - Configure Swagger  
 
Startup.cs
  1. using Microsoft.AspNetCore.Builder;  
  2. using Microsoft.AspNetCore.Hosting;  
  3. using Microsoft.AspNetCore.HttpsPolicy;  
  4. using Microsoft.AspNetCore.Mvc;  
  5. using Microsoft.Extensions.Configuration;  
  6. using Microsoft.Extensions.DependencyInjection;  
  7. using Microsoft.Extensions.Hosting;  
  8. using Microsoft.Extensions.Logging;  
  9. using Microsoft.OpenApi.Models;  
  10. using System;  
  11. using System.Collections.Generic;  
  12. using System.IO;  
  13. using System.Linq;  
  14. using System.Reflection;  
  15. using System.Threading.Tasks;  
  16.   
  17. namespace Swagger  
  18. {  
  19.     public class Startup  
  20.     {  
  21.         public Startup(IConfiguration configuration)  
  22.         {  
  23.             Configuration = configuration;  
  24.         }  
  25.   
  26.         public IConfiguration Configuration { get; }  
  27.   
  28.         // This method gets called by the runtime. Use this method to add services to the container.  
  29.         public void ConfigureServices(IServiceCollection services)  
  30.         {  
  31.             services.AddControllers();  
  32.             services.AddSwaggerGen(swagger =>  
  33.             {  
  34.                 swagger.SwaggerDoc("v1"new OpenApiInfo  
  35.                 {  
  36.                     Version = "v1",  
  37.                     Title = "Swagger Document API's",  
  38.                     Description = $"Document your already existing API's with Swagger \r\n\r\n © Copyright {DateTime.Now.Year}. All rights reserved."  
  39.                 });  
  40.                 #region XMl Documentation  
  41.                 var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";  
  42.                 var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);  
  43.                 swagger.IncludeXmlComments(xmlPath);  
  44.                 #endregion  
  45.             });  
  46.         }  
  47.   
  48.         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.  
  49.             public void Configure(IApplicationBuilder app, IWebHostEnvironment env)  
  50.         {  
  51.             if (env.IsDevelopment())  
  52.             {  
  53.                 app.UseDeveloperExceptionPage();  
  54.             }  
  55.   
  56.             app.UseHttpsRedirection();  
  57.   
  58.             app.UseRouting();  
  59.   
  60.   
  61.             app.UseAuthorization();  
  62.   
  63.             app.UseEndpoints(endpoints =>  
  64.             {  
  65.                 endpoints.MapControllers();  
  66.             });  
  67.             app.UseSwagger();  
  68.             app.UseSwaggerUI(o =>  
  69.             {  
  70.                 o.SwaggerEndpoint("/swagger/v1/swagger.json""Swagger");  
  71.             });  
  72.         }  
  73.     }  
  74. }  
launchSettings.json
  1. {  
  2.   "$schema""http://json.schemastore.org/launchsettings.json",  
  3.   "iisSettings": {  
  4.     "windowsAuthentication"false,  
  5.     "anonymousAuthentication"true,  
  6.     "iisExpress": {  
  7.       "applicationUrl""http://localhost:62614",  
  8.       "sslPort": 44380  
  9.     }  
  10.   },  
  11.   "profiles": {  
  12.     "IIS Express": {  
  13.       "commandName""IISExpress",  
  14.       "launchBrowser"true,  
  15.       "launchUrl""swagger/index.html",  
  16.       "environmentVariables": {  
  17.         "ASPNETCORE_ENVIRONMENT""Development"  
  18.       }  
  19.     },  
  20.     "Swagger": {  
  21.       "commandName""Project",  
  22.       "launchBrowser"true,  
  23.       "launchUrl""swagger/index.html",  
  24.       "applicationUrl""https://localhost:5001;http://localhost:5000",  
  25.       "environmentVariables": {  
  26.         "ASPNETCORE_ENVIRONMENT""Development"  
  27.       }  
  28.     }  
  29.   }  
  30. }  
XML Comments
 
In our XML Comments for methods.
 
WeatherController.cs
  1. using Microsoft.AspNetCore.Mvc;  
  2. using Microsoft.Extensions.Logging;  
  3. using System;  
  4. using System.Collections.Generic;  
  5. using System.ComponentModel.DataAnnotations;  
  6. using System.Linq;  
  7. using System.Threading.Tasks;  
  8.   
  9. namespace Swagger.Controllers  
  10. {  
  11.     [ApiController]  
  12.     [Route("[controller]")]  
  13.     public class WeatherForecastController : ControllerBase  
  14.     {  
  15.         private static readonly string[] Summaries = new[]  
  16.         {  
  17.             "Freezing""Bracing""Chilly""Cool""Mild""Warm""Balmy""Hot""Sweltering""Scorching"  
  18.         };  
  19.   
  20.         private readonly ILogger<WeatherForecastController> _logger;  
  21.   
  22.         public WeatherForecastController(ILogger<WeatherForecastController> logger)  
  23.         {  
  24.             _logger = logger;  
  25.         }  
  26.   
  27.         /// <summary>  
  28.         /// Weather Forecast Get Method  
  29.         /// </summary>  
  30.         /// <returns>Json Data</returns>  
  31.         [HttpGet]  
  32.         public IEnumerable<WeatherForecast> Get()  
  33.         {  
  34.             var rng = new Random();  
  35.             return Enumerable.Range(1, 5).Select(index => new WeatherForecast  
  36.             {  
  37.                 Date = DateTime.Now.AddDays(index),  
  38.                 TemperatureC = rng.Next(-20, 55),  
  39.                 Summary = Summaries[rng.Next(Summaries.Length)]  
  40.             })  
  41.             .ToArray();  
  42.         }  
  43.   
  44.         /// <summary>  
  45.         /// Post method in weather controller.  
  46.         /// </summary>  
  47.         /// <remarks>  
  48.         /// Here is the sample to show remarks  
  49.         /// </remarks>  
  50.         /// <param name="Id">Pass the Id</param>  
  51.         /// <returns>Returns a Post Message</returns>  
  52.         [HttpPost]  
  53.         public IActionResult Post([Required] int Id)  
  54.         {  
  55.             return Ok();  
  56.         }  
  57.     }  
  58. }  
 Here are XML nodes in use:
  • Summary: A high-level summary of what are method /class/field is or does.
  • remarks: Additional detail about the method/class/field
  • param:   A parameter to the method, and what it represents
  • returns:  A description of what the method returns.
Output - View Swagger
 
 
 Here is a clear description of what is what in Swagger UI
 
 
Github URL:  Swagger
 
Thanks for reading this article, Hope this article helps you!!!
 
Keep Learning.... !!!