How to integrate Swagger UI in a .NET Core Web API application

Swagger is an open-source programming system that helps engineers configuration, fabricate, record, and devour RESTful Web API. Strut is well known for its Swagger UI that permits designers to test their Web APIs. Nonetheless, Swagger toolset upholds mechanized documentation, code age, and robotized testing including experiments.

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.

app.UseSwagger();       
app.UseSwaggerUI(c=>    
{    
   c.SwaggerEndpoint(“/swagger/v1/swagger.json”,”MyAPI”);    
});   
 

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.

services.AddSwaggerGen(c=>  
   {  
      c.SwaggerDoc(“v1”,new Info  
      {  
         version = “v1”,  
         title = “MyAPI”,  
         description = “Testing”  
      });  
   });  

Step 4 - launchSettings.json

Add “swagger” as launchUrl in IIS Express.

Example

"profiles" : {  
   "IIS Express" : {  
      "commandName" : "IISExpress",  
         "launchBrowser" : true,  
         "launchUrl" : "swagger",  
      "environmentVariables" : {  
   "ASPNETCORE_ENVIRONMENT" : "Development"  
      }  
   }  
}  

Step 5 - Add Route to Controller

Add Route Attribute in each API methods.

Example

[HttpGet]  
[Route(“api/values/list”)]  
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. 

Post a Comment

0 Comments