Implement Swagger UI With Web API

What is Swagger? 
 
Swagger is a simple yet powerful representation of your RESTful API. With the largest ecosystem of API tooling on the planet, thousands of developers are supporting Swagger in almost every modern programming language and deployment environment.
 
Step 1 Adding Swagger to Web API Project
 
To add Swagger to Web API, we just need to install an open source project called Swashbuckle via NuGet.

 
 
Step 2 Install Swagger from NuGet.
 
 
 
After Installation, you can see the swaggerconfig.cs under app_start folder in your respective project.

Step 3 View the Swaggerconfig.cs 

 
 
Step 4 Configuring Swagger

At minimum, we need this line to enable Swagger and Swagger UI. 
  1. GlobalConfiguration.Configuration  
  2. .EnableSwagger(c => c.SingleApiVersion("Version""Project Name"))  
  3. .EnableSwaggerUi();  
Example
  1. GlobalConfiguration.Configuration  
  2. .EnableSwagger(c => c.SingleApiVersion("v1""TS_EF_API"));  
  3. .EnableSwaggerUi();  
Step 5 Now, run your API application.

 
 
Step 6

Just type swagger after service. You will get the UI of swagger with list API including whatever we wrote in services.

example - http://localhost:1025/swagger/ui/index 



Step 7

Just click one API to view respective data. Click "Try it out" button to view the result.

 
 
Step 8

Enable Swagger to use XML comments
  1. Just right click on your project and go to Properties.
  2. Select "Build" tab.
  3. Check XML Documentation file under output group.

Step 9

Replace c.IncludeXmlComments(path) in swaggerconfig.cs 

example 

c.IncludeXmlComments(string.Format(@"{0}\bin\TS_EF-API.XML", System.AppDomain.CurrentDomain.BaseDirectory));

 
 
 

Step 10

You can see the warning and suggestion from swagger

So here, we need to add the comments to each and every class, method and properties. While adding comments, we need to mention proper remarks.

Warning

 

So we are going to add the comments to everything so as to make proper API. 
  1. using System.Collections.Generic;  
  2. using System.Net;  
  3. using System.Net.Http;  
  4. using System.Web.Http;  
  5. using System.Web.Http.Description;  
  6. using TS_EF_API.Repository;  
  7. namespace TS_EF_API.Controllers {  
  8.     /// <summary>  
  9.     /// Company  
  10.     /// </summary>  
  11.     public class CompanyController: ApiController   
  12.     {#region Global Declaration  
  13.         private IRepository < Company > _Companyrepository = null;  
  14.         /// <summary>  
  15.         /// Constructor for Company Controller  
  16.         /// </summary>  
  17.         public CompanyController() {  
  18.             this._Companyrepository = new Repository < Company > ();  
  19.         }#endregion  
  20.         #region Company  
  21.             /// <summary>  
  22.             /// Get Company List  
  23.             /// </summary>  
  24.             /// <returns code="200"></returns>  
  25.             [ResponseType(typeof(IEnumerable < Company > ))]  
  26.             [Route("api/GetCompanies")]  
  27.             [HttpGet]  
  28.         public HttpResponseMessage GetCompanies() {  
  29.             var result = _Companyrepository.GetAll();  
  30.             HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, result);  
  31.             return response;  
  32.         }  
  33.         /// <summary>  
  34.         /// Get Company Detail  
  35.         /// </summary>  
  36.         /// <param name="CompanyId"></param>  
  37.         /// <returns code="200"></returns>  
  38.         [ResponseType(typeof(Company))]  
  39.         [Route("api/GetCompany")]  
  40.         [HttpGet]  
  41.         public HttpResponseMessage GetCompany(int CompanyId) {  
  42.             var result = _Companyrepository.GetById(CompanyId);  
  43.             HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, result);  
  44.             return response;  
  45.         }#endregion  
  46.     }  
  47. }  
models, 
  1. //------------------------------------------------------------------------------  
  2. // <auto-generated>  
  3. // This code was generated from a template.  
  4. //  
  5. // Manual changes to this file may cause unexpected behavior in your application.  
  6. // Manual changes to this file will be overwritten if the code is regenerated.  
  7. // </auto-generated>  
  8. //------------------------------------------------------------------------------  
  9. namespace TS_EF_API   
  10. {  
  11.     using System;  
  12.     using System.Collections.Generic;  
  13.     /// <summary>  
  14.     /// Company Modal  
  15.     /// </summary>  
  16.     public partial class Company {  
  17.         /// <summary>  
  18.         /// Company Id  
  19.         /// </summary>  
  20.         public int CompanyID {  
  21.             get;  
  22.             set;  
  23.         }  
  24.         /// <summary>  
  25.         /// CompanyName  
  26.         /// </summary>  
  27.         public string CompanyName {  
  28.             get;  
  29.             set;  
  30.         }  
  31.         /// <summary>  
  32.         /// Company MailingAddress1  
  33.         /// </summary>  
  34.         public string MailingAddress1 {  
  35.             get;  
  36.             set;  
  37.         }  
  38.         /// <summary>  
  39.         ///Company MailingAddress2  
  40.         /// </summary>  
  41.         public string MailingAddress2 {  
  42.             get;  
  43.             set;  
  44.         }  
  45.     }  
  46. }   
Step 11 Now, just rebuild and run your Service
 
http://localhost:1025/swagger/docs/v1 ------> now you can see this URL in Swagger UI, and just copy that url and paste in another table
 
Step 12

http://localhost:1025/swagger/docs/v1

 
Here, you can see API data is available in JSON format. Now, we need to convert this as document.

Step 13

Search in Google for JSON formatter.

 
Step 14

Paste that JSON data and click "Process".

 
 
After this, you will get to know whether the json is valid or not and you will get the standard form structure with document.

 
 
Click download button to view full service document. This document is enough to review your full API and check whether you wrote it in proper way or not.
 
Example of documentation
  1. {  
  2.     "swagger""2.0",  
  3.     "info": {  
  4.         "version""v1",  
  5.         "title""TS_EF_API"  
  6.     },  
  7.     "host""localhost:1025",  
  8.     "schemes": ["http"],  
  9.     "paths": {  
  10.         "/api/GetCompanies": {  
  11.             "get": {  
  12.                 "tags": ["Company"],  
  13.                 "summary""Get Company List",  
  14.                 "operationId""Company_GetCompanies",  
  15.                 "consumes": [],  
  16.                 "produces": ["application/json""text/json""application/xml""text/xml"],  
  17.                 "responses": {  
  18.                     "200": {  
  19.                         "description""OK",  
  20.                         "schema": {  
  21.                             "type""array",  
  22.                             "items": {  
  23.                                 "$ref""#/definitions/Company"  
  24.                             }  
  25.                         }  
  26.                     }  
  27.                 }  
  28.             }  
  29.         },  
  30.         "/api/GetCompany": {  
  31.             "get": {  
  32.                 "tags": ["Company"],  
  33.                 "summary""Get Company Detail",  
  34.                 "operationId""Company_GetCompany",  
  35.                 "consumes": [],  
  36.                 "produces": ["application/json""text/json""application/xml""text/xml"],  
  37.                 "parameters": [{  
  38.                     "name""CompanyId",  
  39.                     "in""query",  
  40.                     "description""",  
  41.                     "required"true,  
  42.                     "type""integer",  
  43.                     "format""int32"  
  44.                 }],  
  45.                 "responses": {  
  46.                     "200": {  
  47.                         "description""OK",  
  48.                         "schema": {  
  49.                             "$ref""#/definitions/Company"  
  50.                         }  
  51.                     }  
  52.                 }  
  53.             }  
  54.         }   
Advantages
  1. Standard form of service
  2. Everyone easily understands our code
  3. Easy to test
  4. No need to write document 


Similar Articles