How To Integrate Swagger In an .NET Core Web API

Swagger helps developers design, build, document, and consume RESTful Web API. This blog shows how you can integrate Swagger in your .NET Core Web API project.

Swagger is an open-source software framework that helps developers design, build, document, and consume RESTful Web API. Swagger is popular for its Swagger UI that allows developers to test their Web APIs. However, Swagger toolset supports automated documentation, code generation, and automated testing including test cases.
 

Integrate Swagger UI in .NET Core Web API

 
Here are the steps required to integrate Swagger UI in an .NET Core Web API project.
 
Step 1
 
Create .Net Core WebAPI project using Visual Studio 2017
 
Step 2
 
Install Swashbuckle.AspNetCore package from NuGet
 
Step 3
 
Need to add few these two methods in the Startup.cs class. The details of these methods are below.
  • Configure()
  • ConfigureServices()
Configure() Method
 
Add the below code in Configure() method.
  1. app.UseSwagger();    
  2.     
  3. app.UseSwaggerUI(c=>    
  4. {    
  5.    c.SwaggerEndpoint(“/swagger/v1/swagger.json”,”MyAPI”);    
  6. });     
Note 
Swagger Endpoint has the following parameters,
  • Url – “/swagger/v1/swagger.json”
  • swagger – It should be swagger, because we have to configure this name in launchSettings.json file.
  • v1 – The folder which is created dynamically with this(v1) name.
  • swagger.json – This file generated dynamically inside the v1 folder.
ConfigureServices() Method
 
Add the below code in ConfigureServices() method.
  1. services.AddSwaggerGen(c=>  
  2.    {  
  3.       c.SwaggerDoc(“v1”,new Info  
  4.       {  
  5.          version = “v1”,  
  6.          title = “MyAPI”,  
  7.          description = “Testing”  
  8.       });  
  9.    });  
Step 4 - launchSettings.json
 
Add “swagger” as launchUrl in IIS Express.
 
Example
  1. "profiles" : {  
  2.    "IIS Express" : {  
  3.       "commandName" : "IISExpress",  
  4.          "launchBrowser" : true,  
  5.          "launchUrl" : "swagger",  
  6.       "environmentVariables" : {  
  7.    "ASPNETCORE_ENVIRONMENT" : "Development"  
  8.       }  
  9.    }  
  10. }  
Step 5 - Add Route to Controller
 
Add Route Attribute in each API methods.
 
Example
  1. [HttpGet]  
  2. [Route(“api/values/list”)]  
  3. Public ActionResult Get(){ }  
Sample Swagger UI
 
Now, when you build and use your API project, you have /Swagger/ (see below) available for your API project that can be used to test your API without writing any additional code. 
 
How To Integrate Swagger In an .NET Core Web API