Integrate Swagger UI In ASP.NET Core Web API

Introduction

In this article, we are going to learn about how to integrate Swagger UI in the ASP.NET Core Web API application. 

Why Swagger

The API documentation is used to effectively use and integrate the API in our project. The API documentation should have details about each APIs such as mandatory parameters, optional parameters, and how the output/result and errors would be for various scenarios. The proper API documentation will help consumers to understand and integrate our APIs into their projects.

Swagger is a language-agnostic specification for describing REST APIs. The Swagger is also referred to as OpenAPI. It allows us to understand the capabilities of API without looking at the actual implementation code. Swagger used to reduce the work needed while integrating an API. Similarly, it also helps API developers to document their APIs quickly and effectively.

Swagger UI

Swagger UI offers a web-based UI that provides information about the service, using the generated OpenAPI specification. The Swashbuckle package has an embedded version of Swagger UI, so that it can be hosted in our ASP.NET Core app using a middleware. Each public action method in the controllers is available in the Swagger UI.

Integrating Swagger UI in the ASP.NET Core Web API

We can use the Swashbuckle package to integrate Swagger into our .NET Core Web API project. It will generate the Swagger specification and a Swagger UI for our project.

There are three main components in the Swashbuckle package.

  • Swashbuckle.AspNetCore.Swagger: This contains the Swagger object model and the middleware to expose SwaggerDocument objects as JSON endpoints.
  • Swashbuckle.AspNetCore.SwaggerGen: A Swagger generator that builds SwaggerDocument objects directly from our routes, controllers, and models. 
  • Swashbuckle.AspNetCore.SwaggerUI: An embedded version of the Swagger UI and it interprets Swagger JSON to build a rich, customizable experience for describing the web API functionality. It includes built-in test harnesses for the public methods.

To enable the swagger we need to follow the below steps.

Step 1 

Install Swashbuckle.AspNetCore package using the NuGet Package Manager or NuGet Package Console in the Visual Studio.

Step 2

Add the Swagger generator to the services collection in the Startup.ConfigureServices method.

public void ConfigureServices(IServiceCollection services)
{
    services.AddSwaggerGen();
}

In the Startup.Configure() method, enable the middleware for serving the generated JSON document and the Swagger UI.

app.UseSwagger();

app.UseSwaggerUI(c =>
{
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "Sample API");
});

Step 3

Let's consider the below Employee controller and Employee model.

Employe.cs

public class Employee
{
	public int Id { get; set; }

	public string FirstName { get; set; }

	public string LastName { get; set; }

	public string EmailId { get; set; }
}

EmployeController.cs

[Route("[controller]")]
[ApiController]
public class EmployeeController : ControllerBase
{
	[HttpGet]
	[Produces("application/json")]
	public IEnumerable<Employee> Get()
	{
		return GetEmployeesDeatils();
	}

	[HttpGet("{id}")]
	[Produces("application/json")]
	public Employee Get(int id)
	{
		return GetEmployeesDeatils().Find(e => e.Id == id);
	}

	[HttpPost]
	[Produces("application/json")]
	public Employee Post([FromBody] Employee employee)
	{
		// Write logic to insert employee data
		return new Employee()
		{
			Id = 4,
			FirstName = employee.FirstName,
			LastName = employee.LastName,
			EmailId = employee.EmailId
		};
	}

	private List<Employee> GetEmployeesDeatils()
	{
		return new List<Employee>()
		{
			new Employee()
			{
				Id = 1,
				FirstName= "Test",
				LastName = "Name",
				EmailId ="[email protected]"
			},
			new Employee()
			{
				Id = 2,
				FirstName= "Test",
				LastName = "Name1",
				EmailId ="[email protected]"
			}
		};
	}
}

Step 4

Press F5 to run the API locally and to launch the Swagger UI just hit the http://localhost:<port_number>/swagger/index.html URL in the browser. The Swagger UI for above controller looks as follows,

Hit the http://localhost:<port_number>/swagger/v1/swagger.json URL in the browser. We can see the OpenAPI specification (openapi.json).

Step 5

Just expand the required operation and click "Try it out" button.

Step 6

Enter the input values and click the "Execute" button to run the API. The response will be displayed as follows.

Customize and extend the Swagger

1) We can customize the Swagger UI based on our needs. We can add API information, author, license, and description details in the Swagger UI. Using OpenApiInfo class we can add those details in the AddSwaggerGen() method in the Startup.ConfigureServices().

public void ConfigureServices(IServiceCollection services)
{
	services.AddSwaggerGen(options =>
	{
	    options.SwaggerDoc("v1", new OpenApiInfo
	    {
	        Version = "v1",
	        Title = "Sample API",
	        Description = "Sample API for Swagger integration",
	        TermsOfService = new Uri("https://test.com/terms"), // Add url of term of service details
			Contact = new OpenApiContact
			{
				Name = "Test Contact",
				Url = new Uri("https://test.com/contact") // Add url of contact details
			},
			License = new OpenApiLicense
			{
				Name = "Test License",
				Url = new Uri("https://test.com/license") // Add url of license details
			}
	    });
	});
}

Now the Swagger UI displays the above updated information.


2) For enabling XML comments, we need to follow the below steps.

Goto the project Properties -> Build tab, 

  • Add 1591 to Suppress warning. Suppress warning about any method, class, or field that doesn’t have triple-slash comments.
  • Check the "XML documentation file" check box. Let’s keep the auto-generated file path.

In the Startup.ConfigureServices() method, configure Swagger to use the XML file that’s generated in the above step.

public void ConfigureServices(IServiceCollection services)
{
	services.AddSwaggerGen(options =>
	{
	    options.SwaggerDoc("v1", new OpenApiInfo
	    {
	        Version = "v1",
	        Title = "Sample API",
	        Description = "Sample API for Swagger integration",
	        TermsOfService = new Uri("https://test.com/terms"), // Add url of term of service details
			Contact = new OpenApiContact
			{
				Name = "Test Contact",
				Url = new Uri("https://test.com/contact") // Add url of contact details
			},
			License = new OpenApiLicense
			{
				Name = "Test License",
				Url = new Uri("https://test.com/license") // Add url of license details
			}
	    });
	
		var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
	    var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
	    options.IncludeXmlComments(xmlPath);
	});
}

Now, adding triple-slash comments(///) to the action method which provides more information (such as description, response details, etc) about action methods in the section headers of the Swagger UI.

Let's add a summary, remarks, response details to the actions.

EmployeeController.cs

[Route("[controller]")]
[ApiController]
public class EmployeeController : ControllerBase
{
	/// <summary>
	/// Gets the list of all Employees.
	/// </summary>
	/// <returns>The list of Employees.</returns>
	/// <response code="200">Returns the items</response>
	[HttpGet]
	[Produces("application/json")]
	[ProducesResponseType(StatusCodes.Status200OK)]
	public IEnumerable<Employee> Get()
	{
		return GetEmployeesDeatils();
	}

	[HttpGet("{id}")]
	[Produces("application/json")]
	public Employee Get(int id)
	{
		return GetEmployeesDeatils().Find(e => e.Id == id);
	}

	/// <summary>
	/// Creates an Employee.
	/// </summary>
	/// <remarks>
	/// Sample request:
	/// 
	///     POST /Employee
	///     {        
	///       "firstName": "Test",
	///       "lastName": "Name",
	///       "emailId": "[email protected]"        
	///     }
	/// </remarks>
	/// <param name="employee"></param>
	/// <response code="201">Returns the newly created item</response>
	/// <response code="400">If the item is null</response>
	[HttpPost]
	[Produces("application/json")]
	[ProducesResponseType(StatusCodes.Status201Created)]
	public Employee Post([FromBody] Employee employee)
	{
		// Write logic to insert employee data
		return new Employee()
		{
			Id = 4,
			FirstName = employee.FirstName,
			LastName = employee.LastName,
			EmailId = employee.EmailId
		};
	}

	private List<Employee> GetEmployeesDeatils()
	{
		return new List<Employee>()
		{
			new Employee()
			{
				Id = 1,
				FirstName= "Test",
				LastName = "Name",
				EmailId ="[email protected]"
			},
			new Employee()
			{
				Id = 2,
				FirstName= "Test",
				LastName = "Name1",
				EmailId ="[email protected]"
			}
		};
	}
}

The Swagger UI will be displayed with updated values (summary, remarks, response details) as follows,

3) We can also mention the required fields by adding the [Required] attribute to the corresponding field of the Employee model.

public class Employee
{
	public int Id { get; set; }

	[Required]
	public string FirstName { get; set; }

	[Required]
	public string LastName { get; set; }

	[Required]
	public string EmailId { get; set; }
}

The Swagger UI will be displayed with updated value of Employee model as below.

Summary

In this article, we have learned about the following topics,

  • Why API documentation is needed.
  • What is Swagger Specification & Swagger UI.
  • Integrating Swagger UI in the ASP.NET Core Web API application.
  • Customize and Extending the Swagger Documentation.