How To Implement Swagger In ASP.NET Core Web API

Introduction

 
Swagger (Open API) is a language-agnostic specification for describing and documenting the REST API. Swagger allows both the machine and developer to understand the working and capabilities of the machine without direct access to the source code of the project. The main objectives of swagger (Open API) are to,
  • Minimize the workload to connect with Microservice.
  • Reduce the time needed to accurately document the Microservice.

OpenAPI Implementation Process

 
There are two main implementations of open API For Asp.net Core technologies, like using Swashbuckle and NSwag. I will discuss both one by one in separate articles.
 
OpenAPI vs Swagger
 
Open API Refers to the specification and Swagger refers to the family of the open-source and commercial products from SmartBear that work with the OpenAPI Specification. Subsequent Open-source products such as OpenAPIGenerator also fall under the category of Swagger.
 
In short,
  • OpenAPI is Specification
  • Swagger is the tool the uses OpenAPI Specification for Example OpenAPIGenerator and Swagger UI.
OpenAPI Specification 
 
The OpenAPI Specification is a document that describes the capabilities of our APIs. The Open Specification is based on XML and attributes annotations with the controller and models. It is the main part of the OpenAPI flow and is used to drive the tools such as SwaggerUI by Default. Its name is openapi.json. The given below Jason file is the example of the OpenAPI Specification.
  1. {  
  2.   "openapi""3.0.4",  
  3.   "info": {  
  4.     "title""API V3",  
  5.     "version""v3"  
  6.   },  
  7.   "paths": {  
  8.     "/api/GetPayment": {  
  9.       "get": {  
  10.         "tags": [  
  11.           "GetPayment"  
  12.         ],  
  13.         "operationId""ApiGetPayment",  
  14.         "responses": {  
  15.           "200": {  
  16.             "description""Success",  
  17.             "content": {  
  18.               "text/plain": {  
  19.                 "schema": {  
  20.                   "type""array",  
  21.                   "items": {  
  22.                     "$ref""#/components/schemas/GetPayment"  
  23.                   }  
  24.                 }  
  25.               },  
  26.               "application/json": {  
  27.                 "schema": {  
  28.                   "type""array",  
  29.                   "items": {  
  30.                     "$ref""#/components/schemas/GetPayment"  
  31.                   }  
  32.                 }  
  33.               },  
  34.               "text/json": {  
  35.                 "schema": {  
  36.                   "type""array",  
  37.                   "items": {  
  38.                     "$ref""#/components/schemas/GetPayment"  
  39.                   }  
  40.                 }  
  41.               }  
  42.             }  
  43.           }  
  44.         }  
  45.       },  
  46.       "post": {  
  47.         …  
  48.       }  
  49.     },  
  50.     "/api/GetPayment/{id}": {  
  51.       "get": {  
  52.         …  
  53.       },  
  54.       "put": {  
  55.         …  
  56.       },  
  57.       "delete": {  
  58.         …  
  59.       }  
  60.     }  
  61.   },  
  62.   "components": {  
  63.     "schemas": {  
  64.       "ToDoItem": {  
  65.         "type""object",  
  66.         "properties": {  
  67.           "id": {  
  68.             "type""integer",  
  69.             "format""int32"  
  70.           },  
  71.           "name": {  
  72.             "type""string",  
  73.             "nullable"true  
  74.           },  
  75.           "isCompleted": {  
  76.             "type""boolean"  
  77.           }  
  78.         },  
  79.         "additionalProperties"false  
  80.       }  
  81.     }  
  82.   }  
  83. }  

Swagger UI

 
Swagger UI (User Interface) is the web-based UI that provides information about the microservice using the generated Open API Specification. Both Swashbuckle and NSwag include an embedded version of Swagger UI so that it can be hosted in your ASP.NET Core App using a middleware component called the web. The UI Of Swagger looks like below.
 
How To Implement Swagger In ASP.NET Core Web API
Figure 1.1
 
How To Implement Swagger In ASP.NET Core Web API
Figure 1.2
 
How To Implement Swagger In ASP.NET Core Web API 
Figure 1.3
 

Getting Started with Swashbuckle in ASP.NET Core

 
There are three main components of Swashbuckle.
 
Swashbuckle.AspNetCore.Swagger
 
Swashbuckle.AspNetCore.Swagger is the Object Model and Middleware to expose swagger Document as JSON End Points.
 
Swashbuckle.AspNetCore.SwaggerGen
 
A Swagger Generator that builds Swagger Document Objects Directly from your routes controllers and models, this package is combined with Swagger endpoints middleware to automatically expose the Swagger JSON.
 
Swashbuckle.AspNetCore.SwaggerUI
 
Swashbuckle.AspNetCore.SwaggerUI is an embedded version of the Swagger UI Tool. It explains swagger JSON to build a rich customizable practical for explaining the Web API functionality and  it includes a built-in test harnessed for the public Methods.
 

Package Installation

 
Package Installation Using Package Manager Console.
  1. Go to the View> Other Windows > Package Manager Console
  2. Execute the Command
Install-Package Swashbuckle.AspNetCore -version 5.6.3
 
How To Implement Swagger In ASP.NET Core Web API 
 

Package Installation Using Nuget Package Library

 
Install the Package using the Nuget package Library
  1. Right-click on the Project Solution Explorer and select the ManageNuget Packages
  2. Set the Package source to Nuget.org.
  3. Ensure the prerelease option is enabled.
  4. Enter the Name of the package Swashbuckle.AspNetCore.
  5. Select the latest version and hit the installation button.
How To Implement Swagger In ASP.NET Core Web API
 Figure 1.6
 
How To Implement Swagger In ASP.NET Core Web API 
 Figure 1.7
 
Add and Configure the Middleware
 
Add the Middleware component to the startups class in the Startup.ConfigureServices of the project.
 
Startup.ConfigureServices
 
How To Implement Swagger In ASP.NET Core Web API 
 Figure 1.8
 
Code of the project in Configure Services 
  1. public void ConfigureServices(IServiceCollection services) {  
  2.     services.AddControllers();  
  3.     services.AddHttpClient();  
  4.     services.AddMvc();  
  5.     services.AddDbContext < ApplicationDbContext > (options => options.UseSqlServer(_configuration.GetConnectionString("DefaultConnection")));  
  6.     services.AddTransient < IRepository < Payment > , PaymentRepository > ();  
  7.     services.AddTransient < PaymentService, PaymentService > ();  
  8.     services.AddSwaggerGen();  
  9. }   
Startup. Configure
 
How To Implement Swagger In ASP.NET Core Web API
 
Code of the Project in Configure Method 
  1. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {  
  2.     if (env.IsDevelopment()) {  
  3.         app.UseDeveloperExceptionPage();  
  4.     }  
  5.     app.UseRouting();  
  6.     app.UseAuthorization();  
  7.     app.UseEndpoints(endpoints => {  
  8.         endpoints.MapControllers();  
  9.     });  
  10.     app.UseSwagger();  
  11.     app.UseSwaggerUI(c => {  
  12.         c.SwaggerEndpoint("/swagger/v1/swagger.json""My API V2");  
  13.     });  
  14.   }  
  15. }   

Summary

 
Swagger (Open API) is a language-agnostic specification for describing and documenting the REST API. Swagger allows both the machine and the developer to understand the working and capabilities of Machine without direct access to the source code of the project the main objectives of swagger (Open API) are to:
  • Minimize the workload to connect with Microservice.
  • Reduce the time needed to accurately document the Microservice.
Swagger is the Interface Description Language for Describing the RESTful APIs expressed using JSON. Swagger is used to gather a set of open-source software tools to design build documents and use Restful Web Services. Swagger includes automated documentation code generation.  Swashbuckle.AspNetCore.SwaggerUI is an embedded version of the Swagger UI Tool.
 

Conclusion

 
Swagger is the best Open API for documenting the Restful API. As a developer I have had a great experience with Swagger for testing the restful API sending the complete JSON Object and then getting the response in a professional way. It is easy to implement in Asp.net core Web API projects and after the configuration, developers can enjoy the beauty of Swagger Open API.