Implement Swagger UI In ASP.NET Web API Restful Service For Documentation Using Swashbuckle

Introduction

Swagger UI is very powerful documentation tool for Restful services. It is a framework for describing and consuming RESTful APIs. It keeps the documentation system of methods, parameters, and models tightly integrated into the server code. We can add Swashbuckle to any Web API project, and then we can easily customize the generated specification along with the UI (swagger-ui). Swagger UI uses Swashbuckle to displays the documentation.

Description

In this article, I will show the steps to add Swagger in Web API Application to document and test restful Web API services. 

  1. Create Asp.net Web API project using SQL Server
  2. Add Swashbuckle to Asp.net Web API project and displays the Swagger UI documentation

Before going through this article, visit my previous articles as mentioned below.

Steps to be followed,

Step 1: Create a table in database

Create the EmployeeDet table and populate it with sample data as shown here.

CREATE TABLE [dbo].[EmployeeDet](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[FirstName] [nvarchar](50) NULL,
	[LastName] [nvarchar](50) NULL,
	[Gender] [nvarchar](50) NULL,
	[Salary] [int] NULL,
PRIMARY KEY CLUSTERED 
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET IDENTITY_INSERT [dbo].[EmployeeDet] ON 
GO
INSERT [dbo].[EmployeeDet] ([ID], [FirstName], [LastName], [Gender], [Salary]) VALUES (1, N'Mark', N'Hastings', N'Male', 60000)
GO
INSERT [dbo].[EmployeeDet] ([ID], [FirstName], [LastName], [Gender], [Salary]) VALUES (2, N'Steve', N'Pound', N'Male', 45000)
GO
INSERT [dbo].[EmployeeDet] ([ID], [FirstName], [LastName], [Gender], [Salary]) VALUES (3, N'Ben', N'Hoskins', N'Male', 70000)
GO
INSERT [dbo].[EmployeeDet] ([ID], [FirstName], [LastName], [Gender], [Salary]) VALUES (4, N'Philip', N'Hastings', N'Male', 45000)
GO
INSERT [dbo].[EmployeeDet] ([ID], [FirstName], [LastName], [Gender], [Salary]) VALUES (5, N'Mary', N'Lambeth', N'Female', 30000)
GO
INSERT [dbo].[EmployeeDet] ([ID], [FirstName], [LastName], [Gender], [Salary]) VALUES (6, N'Valarie', N'Vikings', N'Female', 35000)
GO
INSERT [dbo].[EmployeeDet] ([ID], [FirstName], [LastName], [Gender], [Salary]) VALUES (7, N'John', N'Stanmore', N'Male', 80000)
GO
SET IDENTITY_INSERT [dbo].[EmployeeDet] OFF
GO

Step 2: Adding ADO.NET Entity Data Model to retrieve data

First, I have created the Web API project named WebAPIProj. Next, I have created the Class Library Project named EmpDataAccess. Right click on EmployeeDataAccess project and select Add - New Item. In the "Add New Item" window Select "Data" from the left pane. Select ADO.NET Entity Data Model named EmpModel. On the Entity Data Model Wizard, select "EF Designer from database" option and click next. On the next screen, click "New Connection" button to provide SQL Server connection details and select proper database name where the EmployeeDet table is available. Then select Entity Framework 6.x and choose "EmployeeDet" table and click Finish. Now I can see the interface of "edmx" as shown below.

Please make sure the EntityFramework package is installed or not from NuGet Package Manager as shown below.

Step 3: Using the Entity Data Model in WebAPIProj project.

Using the Entity Data Model in WebAPIProj project. Right click on the references folder in the WebAPIProj project and select "Add Reference". On the "Reference Manager" screen select "EmpDataAccess" project and click OK. Now we can see that reference or DLL file as shown below. Next, we should build our solution.

Step 4: Adding Web API Controller

Now, I have created the controller named EmployeeController.cs as shown below.

Add following code in EmployeesController.cs.

Code Ref

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using EmpDataAccess;

namespace WebAPIProj.Controllers
{
    public class EmployeeController : ApiController
    {
        public IEnumerable<EmployeeDet> GetDetails()
        {
            using (SatyaDBEntities entities = new SatyaDBEntities())
            {
                return entities.EmployeeDets.ToList();
            }
        }

        public EmployeeDet GetDetails(int id)
        {
            using (SatyaDBEntities entities = new SatyaDBEntities())
            {
                return entities.EmployeeDets.FirstOrDefault(e => e.ID == id);
            }
        }
    }
}

Code Description

Here I have added namespace of class library project in Web API project.

using EmpDataAccess;

Let's have get method GetDetails() which responds to HTTP Get verb. This method is going to return IEnumerable of EmployeeDet object. The EmployeeDet is the generated entity by the ADO.NET Entity Framework based on the EmployeeDet table is database as created earlier. The EmployeeDet has properties that corresponds these columns in EmployeeDet table in Database.

Now create the instance of SatyaDBEntities class. Here SatyaDBEntities is inherited from DbContext class which is responsible for managing databse connection to retrieve the entities.

public IEnumerable < EmployeeDet > GetDetails() {
    using(SatyaDBEntities entities = new SatyaDBEntities()) {
        return entities.EmployeeDets.ToList();
    }
}

This is basically a collection of properties which will return us a list of employees.

return entities.EmployeeDets.ToList();

Now, I have created another Get method with ID parameter named GetDetails(int id) which is going to respond to the URI which has got an ID in it. Here the return type is EmployeeDet.

public EmployeeDet GetDetails(int id) {
    using(SatyaDBEntities entities = new SatyaDBEntities()) {
        return entities.EmployeeDets.FirstOrDefault(e => e.ID == id);
    }
}

Here I want to return one employee based on ID value is given by user.

return entities.EmployeeDets.FirstOrDefault(e => e.ID == id);

Step 5: Adding connecton string in Web.Config of Web API project.

Otherwise, I will get an exception like "No connection string named 'SatyaDBEntities' could be found in the application config file". This is because "Entity Framework" is looking for SatyaDBEntities connection string in the web.config file of WeB API project. SatyaDBEntities connection string is actually in App.config file of EmpDataAccess class library project. Include a copy of this connection string in web.config file.

App.config file of EmpDataAccess:

web.config of Web API project

OUTPUT

Now, I navigate to /api/employee and it should get all employees as shown below.

I navigate to /api/employee/1 and It should get all the details of the employee whose Id=1 as shown below.

Steps To Add Swagger UI For Web API Project

Step 1

I need to install Swashbuckle NuGet package in our Web API project. Swashbuckle is a package or a library that I can make use of in my .NET Web API projects. The Swagger UI is contained within Swashbuckle so if you are developing an API in .NET.

Right click on Web API project and select the Manage NuGet Packages option.

Then install Swashbuckle package as shown below.

Now I can see one class named SwaggerConfig.cs is added under App_Start folder as shown here.

Also, I can see one DLL file is added under References folder as shown below.

Then build the solution and make sure the build is succeeded as shown below.

I navigate to /swagger/ui/index to get the methods of Employee controller as shown below. Like this you can see all ApiController if you have in your Web API project.

Now I will check the Get methods of Employee controller in Swagger UI. That is nothing but the Swagger Documentation.

Now I will check Get method to get list of employees as shown below using Swagger UI.

Click Try it Out to check response as shown below.

Here I can see the most important details on Request URL, Response Body, Response Headers, and Response Code.

Now I will check other Get method with ID parameter to get details of employees of ID=1 as shown below using Swagger UI.

The output is as shown below with Request URL, Response Body, Response Headers, and Response Code.

Summary

In this write-up, we have learned the below details,

  1. Create Asp.net Web API project using SQL Server
  2. Add Swashbuckle to Asp.net Web API project and displays the Swagger UI documentation

Thank You & Stay Tuned For More


Similar Articles