Swagger UI Integration With Web API For Testing And Documentation

In this article, we will learn how to integrate Swashbuckle/Swagger in Web API application and generate a rich UI interface document for API testing.

Small exercises

  1. Create a Web API application.
  2. Add controller with actions using Entity Framework.
  3. Add Swashbuckle/Swagger from  NuGet Package Manager.

Here, in this small example, I will create a Web API application with a few Get and Post methods using API controller and will integrate swagger with this application and create a rich UI Interface document for our API application. Please follow the below steps for the same.

Step 1 - Create Web API application using Visual Studio

Create a new project or add a project to the existing solution. Here, I have added a Web API project to the existing solution.

 ASP.NET
 
ASP.NET 

Step 2 - Create Employee class

 Add a new class with the following properties.

  1. public class Employee  
  2. {  
  3.     public int EmployeeId { getset; }  
  4.   
  5.     public string FirstName { getset; }  
  6.   
  7.     public string LastName { getset; }  
  8.   
  9.     public string City { getset; }  
  10.   
  11.     public string ZipCoe { getset; }  
  12.   
  13. }  

Step 3 - Add new Controller

Create an API controller using a scaffold template and select employee model. Once we are done with the controller, it will create all action methods like Get, Post, put and delete.

ASP.NET 
ASP.NET 

Add Controller with read and write access.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Data;  
  4. using System.Data.Entity;  
  5. using System.Data.Entity.Infrastructure;  
  6. using System.Linq;  
  7. using System.Net;  
  8. using System.Net.Http;  
  9. using System.Web.Http;  
  10. using System.Web.Http.Description;  
  11. using SwaggerIntegrationDemo.Models;  
  12.   
  13. namespace SwaggerIntegrationDemo.Controllers  
  14. {  
  15.     public class EmployeesController : ApiController  
  16.     {  
  17.         private SwaggerIntegrationDemoContext db = new SwaggerIntegrationDemoContext();  
  18.   
  19.   
  20.         // GET: api/Employees  
  21.   
  22.         ////////////////////////////////////////////////////////////////////////////////////////////////////  
  23.         /// <summary>   Gets the employees. </summary>  
  24.         ///  
  25.         /// <remarks> List of all employees </remarks>  
  26.         ///  
  27.         /// <returns>   The employees. </returns>  
  28.         ////////////////////////////////////////////////////////////////////////////////////////////////////  
  29.   
  30.         public IQueryable<Employee> GetEmployees()  
  31.         {  
  32.             return db.Employees;  
  33.         }  
  34.   
  35.         // GET: api/Employees/5  
  36.         ////////////////////////////////////////////////////////////////////////////////////////////////////  
  37.         /// <summary>Get Employee by Id. </summary>  
  38.         ///  
  39.         /// <remarks> Employee Details for Requested employeId </remarks>  
  40.         ///  
  41.         /// <returns>Returns Employee object </returns>  
  42.         ////////////////////////////////////////////////////////////////////////////////////////////////////  
  43.         [ResponseType(typeof(Employee))]  
  44.         public IHttpActionResult GetEmployee(int id)  
  45.         {  
  46.             Employee employee = db.Employees.Find(id);  
  47.             if (employee == null)  
  48.             {  
  49.                 return NotFound();  
  50.             }  
  51.   
  52.             return Ok(employee);  
  53.         }  
  54.   
  55.         // POST: api/Employees  
  56.         ////////////////////////////////////////////////////////////////////////////////////////////////////  
  57.         /// <summary>Create New Employee </summary>  
  58.         ///  
  59.         /// <remarks> Creates new employee using PostEmployee method </remarks>  
  60.         ///  
  61.         /// <returns></returns>  
  62.         ////////////////////////////////////////////////////////////////////////////////////////////////////  
  63.         [ResponseType(typeof(Employee))]  
  64.         public IHttpActionResult PostEmployee(Employee employee)  
  65.         {  
  66.             if (!ModelState.IsValid)  
  67.             {  
  68.                 return BadRequest(ModelState);  
  69.             }  
  70.   
  71.             db.Employees.Add(employee);  
  72.             db.SaveChanges();  
  73.   
  74.             return CreatedAtRoute("DefaultApi"new { id = employee.EmployeeId }, employee);  
  75.         }  
  76.   
  77.         // DELETE: api/Employees/5  
  78.         ////////////////////////////////////////////////////////////////////////////////////////////////////  
  79.         /// <summary>Delete Existing Employee By Id </summary>  
  80.         ///  
  81.         /// <remarks> Delete requested employee </remarks>  
  82.         ///  
  83.         /// <returns></returns>  
  84.         ////////////////////////////////////////////////////////////////////////////////////////////////////  
  85.         [ResponseType(typeof(Employee))]  
  86.         public IHttpActionResult DeleteEmployee(int id)  
  87.         {  
  88.             Employee employee = db.Employees.Find(id);  
  89.             if (employee == null)  
  90.             {  
  91.                 return NotFound();  
  92.             }  
  93.   
  94.             db.Employees.Remove(employee);  
  95.             db.SaveChanges();  
  96.   
  97.             return Ok(employee);  
  98.         }  
  99.   
  100.         protected override void Dispose(bool disposing)  
  101.         {  
  102.             if (disposing)  
  103.             {  
  104.                 db.Dispose();  
  105.             }  
  106.             base.Dispose(disposing);  
  107.         }  
  108.   
  109.         private bool EmployeeExists(int id)  
  110.         {  
  111.             return db.Employees.Count(e => e.EmployeeId == id) > 0;  
  112.         }  
  113.     }  
  114. }  

Step 4 - Add Swashbuckle from NuGet packages

Go to solution and select "Manage NuGet Packages" and search for Swashbuckle to install it. It will integrate swagger to our application.

ASP.NET 

Step 5

Once the above package is installed successfully, we will be able to see SwaggerConfig.cs file under App_Start folder, like in the below code snippet. 

ASP.NET 
  1. using System.Web.Http;  
  2. using WebActivatorEx;  
  3. using SwaggerIntegrationDemo;  
  4. using Swashbuckle.Application;  
  5.   
  6. [assembly: PreApplicationStartMethod(typeof(SwaggerConfig), "Register")]  
  7.   
  8. namespace SwaggerIntegrationDemo  
  9. {  
  10.     public class SwaggerConfig  
  11.     {  
  12.         public static void Register()  
  13.         {  
  14.             var thisAssembly = typeof(SwaggerConfig).Assembly;  
  15.   
  16.             GlobalConfiguration.Configuration  
  17.                 .EnableSwagger(c =>  
  18.                  {  
  19.                          
  20.                         c.SingleApiVersion("v1""Documentation Using Swagger UI");  
  21.   
  22.                        // c.IncludeXmlComments(string.Format(@"                                                  {0}\bin\SwaggerIntegrationDemo.xml", System.AppDomain.CurrentDomain.BaseDirectory));  
  23.   
  24.                        
  25.                  })  
  26.                 .EnableSwaggerUi(c =>  
  27.                  {  
  28.                         c.DocumentTitle("Employee Swagger UI");  
  29.                   });  
  30.         }  
  31.     }  
  32. }  

Step 6

We are done with all required action. Just need to build a solution and it will open with default page of our application.

ASP.NET 

Step 7 - Run Swagger UI for our application

We need to suffix our URL with /swagger. It will create a swagger UI for us.

 ASP.NET

Now, our application is ready with swagger UI and we able to see all our action method in below snippet.

Step 7 - Test API methods using UI

Before moving to testing I want to explain few links which are available in the below screen

  • Show/Hide
    Once we click on this link, it shows all links and if it’s already open then it will hide all actions.

  • List Operation
    It will list out all API action methods

  • Expand operation
    It will expand all operations with try out buttons at the bottom.

This UI generates controller wise operation. Here I have only Employee controller so it’s showing under Employees. If we have more than one controller then it will create another link for that controller.

Here, I have five different API methods for employee controller so it’s created five operations for five methods. Using this UI we can test our API without any other tool.

  • Get
    Using this operation we can fetch all employees

  • Post
    Create new employee using post method

  • Delete
    Delete employee by employee id

  • Put
    Update employee details by employee Id 

 

ASP.NET

Let’s do testing for all API methods using Swagger UI. First, we will create a new employee and then we will retrieve the same employee. Look at the below two snippets,

In first and second snippet I have created the new employee with first name Jaydeep and last name with Patel and city as Rajkot. We able to see at down status code 201 which mean it created a new record with employee id 4 on the server.

In the third snippet, I had tried to fetch the same record with Employee id as 4 and the same employee shown as json response body with response code 200.

 ASP.NET
ASP.NET 
ASP.NET 

Let’s test the Employees Get API method. Click on Try it out button and you will be able to see the list of all employees which we had created using Post method.

 ASP.NET

Like Post and Get employee, we can test all API methods using swagger UI.

If we want to enable documentation for the API method, then follow the below steps.

Step 1

Go to solution build property and check the checkbox for XML documentation file.

 ASP.NET

Step 2

Write XML styled comments top of your all method as below.

  1. // GET: api/Employees    
  2.    
  3.        ////////////////////////////////////////////////////////////////////////////////////////////////////    
  4.        /// <summary>   Gets the employees. </summary>    
  5.        ///    
  6.        /// <remarks> List of all employees </remarks>    
  7.        ///    
  8.        /// <returns>   The employees. </returns>    
  9.        ////////////////////////////////////////////////////////////////////////////////////////////////////    
  10.    
  11.        public IQueryable<Employee> GetEmployees()    
  12.        {    
  13.            return db.Employees;    
  14.        }    
  15.    
  16.        // GET: api/Employees/5    
  17.        ////////////////////////////////////////////////////////////////////////////////////////////////////    
  18.        /// <summary>Get Employee by Id. </summary>    
  19.        ///    
  20.        /// <remarks> Employee Details for Requested employeId </remarks>    
  21.        ///    
  22.        /// <returns>Returns Employee object </returns>    
  23.        ////////////////////////////////////////////////////////////////////////////////////////////////////    
  24.        [ResponseType(typeof(Employee))]    
  25.        public IHttpActionResult GetEmployee(int id)    
  26.        {    
  27.            Employee employee = db.Employees.Find(id);    
  28.            if (employee == null)    
  29.            {    
  30.                return NotFound();    
  31.            }    
  32.    
  33.            return Ok(employee);    
  34.        }  

Step 3 - Enable XML styled document

Enable Documentation in SwaggerConfig.cs file and give XML file path using Includexmlcomments in swagger configuration file as per the below snippet.

ASP.NET

Step 4

Look at the right side in swagger UI screen as below, you are able to comment which was provided in our employee controller API methods as XML styled comments.

 ASP.NET

In the below screen, I have pointed out which comment displayed where in swagger UI. This comment really helps the end user to identify which API action method is doing what by the right side of that operation.

Look in our example we are able to see “Get all the employees” at the right side, it says that this method fetches all employee records. At bit farther down it displayed that this method returns “List of all employees”. Click on Expand operation and you can check all XML styled comments are there with the respective operation.

ASP.NET

At last, I want to point out a few reasons why we should use swagger,
  1. It generates a UI for us to test API methods and it's easy to test bcause it will give an auto generated example of json to pass vaules for our method.
  2. it eliminates need of other tools like Postman, Soap UI, fidler etc. 

I hope you enjoyed this article.

If you want to refer my articles and blogs, please visit this link My Articles and blogs

Thank you for reading.