Swagger with ASP.NET Core Web API

Swagger with ASP.NET Core Web API

Swagger in Web API – APIs allow enterprises to exchange data between systems.  These APIs are just like any application, with the small difference that they don’t have an user interface.  Instead, APIs focus on database operations, validations, executing business rules and other background operations while providing a standard and consistent interface to these activities.

In SOAP world, we use WSDL which is a XML document to describe the service.  WSDL specifies the location and the methods of the service using the XML syntax.  It also defines the message format and protocol details for a web service.

When APIs are exposed to partners or developers, it’s also necessary to provide the consumers of the APIs with a specification similar to WSDL.  This is where Open API (Swagger) comes in.  Open API is a specification for describing, producing, consuming and visualizing RESTful services.  The specification creates the RESTful contract for the API, detailing all of its resources and operations in a human and machine readable format for easy development, discovery and integration. 

In simple words, SOAP has WSDL and REST has Swagger.

For this post we will use ASP.NET Web API to create a RESTful service and use a NuGet package to create Swagger(Open API) specification.  Please refer this link to learn about creating HTTP service with ASP.NET Web API.

What is ASP.NET Web API?

ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework.

 Lets talk about the following steps in the remaining article.

  1. NuGet Packages required
  2. Configure Swagger
  3. Setting up the Controller
  4. Set swagger as startup page 

The sample code used in this post is available in github


 

1. Required NuGet Packages

Install “Swashbuckle.AspNetCore” NuGet package in the solution. 

Swagger Nuget Packages
(Package versions in the image were latest at the time of writing this blog)

2. Configure Swagger

Register Swagger generator in the ConfigureServices method of startup.cs.  

public void ConfigureServices(IServiceCollection services)
{
   services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
   // Register the Swagger generator
   services.AddSwaggerGen(c =>
   {
      c.SwaggerDoc("v1", new Info
      {
         Title = "Employee API",
         Version = "v1",
         Description = "API to manage Employees",
         TermsOfService = "None"
      });
   });
}

The “Info” object used in registering the Swagger generator is from the “Swashbuckle” NuGet package.  It also provides the ability to set contact and license info. Following is the snapshot of the “Info” class.

using System.Collections.Generic;
using Newtonsoft.Json;

namespace Swashbuckle.AspNetCore.Swagger
{
    public class Info
    {
        public Info();

        public string Version { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
        public string TermsOfService { get; set; }
        public Contact Contact { get; set; }
        public License License { get; set; }
        [JsonExtensionData]
        public Dictionary<string, object> Extensions { get; }
    }
}

After the Swagger generator is registered, enable the Swagger middleware in the “Configure” method of startup.cs. 

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
   if (env.IsDevelopment())
   {
      app.UseDeveloperExceptionPage();
   }
   // Enable middleware to serve generated Swagger as a JSON endpoint.
   app.UseSwagger();

   // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), 
   // specifying the Swagger JSON endpoint.
   app.UseSwaggerUI(c =>
   {
      c.SwaggerEndpoint("/swagger/v1/swagger.json", "Employee API V1");
   });
   app.UseMvc();
}

3. Setting up the Controller

We will create a controller for Employee with 2 methods.  Lets instantiate an employee collection in the constructor for the purpose of this PoC.  In real world the data comes from database or other storage.  First method is to fetch all the employees and the second is to get an employee by id.  “ProducesResponseType” attribute of ASP.NET MVC is used in the web methods to tell the response object type and the response code to swagger.  

First method produces a return type of employee list and the second method returns an object of type Employee when a match is found.  If there is no match for the id passed to the API, then an object of type “ErrorResponse” will be returned.

ErrorResponse.cs
public class ErrorResponse
{
    public int ErrorCode { get; set; }
    public string ErrorMessage { get; set; }
}
Employee.cs
public class Employee
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
    public string Title { get; set; }
}
EmployeeController.cs
[Produces("application/json")]
[Route("api/Employees")]
public class EmployeesController : Controller
{
    private List employeeList;
    public EmployeesController()
    {
        employeeList = new List
            {
                new Employee{Id = 1, FirstName="Jane", LastName="Doe", Age = 21, Title = "Developer"},
                new Employee{Id = 2, FirstName="Bob", LastName="Martin", Age = 21, Title = "Architect"}
            };
    }

    [HttpGet]
    [ProducesResponseType(typeof(List), 200)]
    public ActionResult Get()
    {
        return Ok(employeeList);
    }

    [HttpGet]
    [Route("Get")]
    [ProducesResponseType(typeof(Employee), 200)]
    [ProducesResponseType(typeof(ErrorResponse), 400)]
    public ActionResult Get(int id)
    {
        var employee = employeeList.Where(x => x.Id == id).FirstOrDefault();
        if (employee == null)
        {
            return BadRequest(new ErrorResponse { ErrorCode = 404, ErrorMessage = "Employee Not Found" });
        }
        return Ok(employee);
    }
}

4. Set swagger as startup page

Lets see how to set the swagger specification as the startup url for the web api application.  To do this modify the profiles section of launchsettings.json file.  Each profile can have different launchUrl.

{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:28639/",
      "sslPort": 0
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "swagger/index.html",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "EmployeeAPI": {
      "commandName": "Project",
      "launchBrowser": true,
      "launchUrl": "swagger/index.html",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      },
      "applicationUrl": "http://localhost:28640"
    }
  }
}

You will see the following page when you run the application. This page contains all the methods exposed through API. It also provided a test functionality for each of the methods.

Swagger Specification - API List
Swagger Specification Page

When you click on the method listed under an API, you can see a test page. For the methods which accepts parameters, you can enter the values and hit “Execute” button. It will produce the results in the page similar to the one below.

Swagger Specification - API Test
Swagger – Test Functionality

Recommended Courses

We may receive a commission for purchases made through these links.

This Post Has One Comment

Leave a Reply

Close Menu
Share via
Copy link
Powered by Social Snap