Skip to content

ASP.NET Swagger

ASP.NET Swagger

ASP.NET Swagger is a great library for documenting, generating client code, and testing Web APIs. In this article, we’ll walk through the process of configuring Swagger in an ASP.NET Web API application using .NET 7.0.

 

What’s in this article?

  • Creating a New ASP.NET Web API Project
  • Swagger UI
  • Configuring Swagger in ASP.NET Web API
  • Swagger UI Configuration
  • Documenting Response Types
  • Enabling XML Documents
  • Swagger Code Generation
  • Summary

 

Creating a New ASP.NET Web API Project

First, let’s create a new ASP.NET Web API project, add a controller named EmployeesController and copy the following implementation into it.

using Microsoft.AspNetCore.Mvc;

namespace WebApiSwagger.Controllers
{
    public class Employee
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
    }

    [ApiController]
    [Route("[controller]")]
    public class EmployeesController : ControllerBase
    {
        private static List<Employee> employees = new List<Employee>()
        {
            new Employee() { Id = 1, Name = "John Doe", Email = "johndoe@example.com" },
            new Employee() { Id = 2, Name = "Jane Doe", Email = "janedoe@example.com" }
        };


        [HttpGet]
        public IActionResult Get()
        => Ok(employees);


        [HttpGet("{id}")]
        public IActionResult Get(int id)
        {
            var employee = employees.FirstOrDefault(e => e.Id == id);

            if (null == employee)
                return NoContent();

            return Ok(employee);
        }


        [HttpPost]
        public IActionResult Post([FromBody] Employee employee)
        {
            employees.Add(employee);
            return CreatedAtAction(nameof(Get), new { employee.Id }, employee);
        }

        [HttpPut("{id}")]
        public IActionResult Put(int id, [FromBody] Employee employee)
        {
            if (id != employee.Id)
            {
                return BadRequest();
            }

            var index = employees.FindIndex(e => e.Id == id);
            if (index == -1)
            {
                return NotFound();
            }
            employees[index] = employee;
            return NoContent();
        }

        [HttpDelete("{id}")]
        public IActionResult Delete(int id)
        {
            employees.RemoveAll(e => e.Id == id);
            return NoContent();
        }
    }
}

If you want to learn more about REST APIs including the code above consider reading my REST API article.

Swagger UI

Run the app and open the `http://localhost:5204/swagger` URL in your browser (replace the 5204 with your app’s port).

ASP.NET Swagger

This is an interactive documentation of your API.

The Swagger UI for the Employee API endpoints is generated from the OpenAPI Specification, which is a standard for describing RESTful APIs. The OpenAPI Specification for the Employee API is generated automatically by `Microsoft.AspNetCore.OpenApi` package that provides integration between ASP.NET Web API and the OpenAPI Specification. The package is added to the project and configured to generate the Swagger UI based on the OpenAPI Specification. This allows users to interact with the API and test its endpoints using a user-friendly interface.

here are the steps to use the Swagger UI to test the Employee API endpoints:

  • Explore the Employee API documentation: In the Swagger UI, you can see the different endpoints available in the Employee API. You can expand each endpoint to see the available HTTP methods, such as GET, POST, PUT, and DELETE. You can also see the request and response schema for each endpoint.
  • Test the GET endpoint: To test the GET endpoint for retrieving all employees, click on the GET /Employees endpoint in the Swagger UI. This will expand the endpoint and show the available parameters. Click the Try it out button, and then click the Execute button to send the request to the server. You should see a response with a list of all employees.
  • Test the GET by ID endpoint: To test the GET by ID endpoint for retrieving a single employee, click on the GET /Employees/{id} endpoint in the Swagger UI. This will expand the endpoint and show the available parameters. Enter an ID value in the id parameter, and then click the Try it out button. Click the Execute button to send the request to the server. You should see a response with the details of the employee with the specified ID.
  • Test the POST endpoint: To test the POST endpoint for creating a new employee, click on the POST /Employees endpoint in the Swagger UI. This will expand the endpoint and show the available parameters. Enter the details of a new employee in the body parameter, and then click the Try it out button. Click the Execute button to send the request to the server. You should see a response with the details of the new employee that was created.
  • Test the PUT endpoint: To test the PUT endpoint for updating an existing employee, click on the PUT /Employees/{id} endpoint in the Swagger UI. This will expand the endpoint and show the available parameters. Enter an ID value in the id parameter, and the updated details of the employee in the `employee` parameter in the requests body text area. Click the Try it out button, and then click the Execute button to send the request to the server.
  • Test the DELETE endpoint: To test the DELETE endpoint for deleting an existing employee, click on the DELETE/Employees/{id} endpoint in the Swagger UI. This will expand the endpoint and show the available parameters. Enter an ID value in the id parameter, and then click the Try it out button. Click the Execute button to send the request to the server. You should see a response indicating that the employee was deleted.

Swagger UI provides a user-friendly interface to test API endpoints. By following these steps, you can easily test each endpoint and see the response from the server.

You can also find a JSON representation of the generated document in the following address;

ASP.NET Swagger

 

 

Configuring Swagger in ASP.NET Web API

Open the Program.cs and configure the swagger document generator as follows:

builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo { Title = "Employees API", Version = "v1" });
});

 

This code adds the Swagger generator to our application’s services, and sets the title and version of our API.

ASP.NET Swagger

 

 

Swagger UI Configuration

Too configure the UI specifically configure it’s middleware like this:

 

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

 

This code configures the Swagger UI middleware in our application, and sets the endpoint for the Swagger JSON document.

ASP.NET Swagger

By the way, did you know that we offer a unique online course that boosts your C# career? Check it out here!

 

 

Documenting Response Types

The only response type in the Swagger documentation is 200(Success). Look at the “Responses” section of the post employees endpoint:

ASP.NET Swagger

 

Decorate the post action with the following `[ProducesResponseType]` attributes.

 

        [HttpPost]
        [ProducesResponseType(StatusCodes.Status201Created)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        [ProducesDefaultResponseType]
        public IActionResult Post([FromBody] Employee employee)
        {
            employees.Add(employee);
            return CreatedAtAction(nameof(Get), new { employee.Id }, employee);
        }

 

Run the app and see the “Responses” section of the post employees endpoint again.

ASP.NET Swagger

 

Enabling XML Documents

To make the XML comments affect the swagger, we must add some configurations to the project file and Program.cs.

Open <your project name>.csproj file and add the following:

  <PropertyGroup>
    <!--Include xml comments in swagger UI-->
    <GenerateDocumentationFile>true</GenerateDocumentationFile>
  </PropertyGroup>

 

Likewise, open your `Program.cs` file and add the following parameters to AddSwaggerGen.

        builder.Services.AddSwaggerGen(c =>
        {
            //..
            
            var xmlFilename = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
            c.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename));
        });

 

Finally, add the following XML comments to your EmployeesController.Post action.

        /// <summary>
        /// Posts an Employee.
        /// </summary>
        /// <param name="employee"></param>
        /// <returns>The newly added employee</returns>
        /// <remarks>
        /// Request Example:
        ///
        ///     POST /Employee
        ///     {
        ///       "id": 1,
        ///       "name": "Mohsen",
        ///       "email": "Mohsen.Bazmi@Example.com"
        ///     }
        ///
        /// </remarks>
        /// <response code="201">Returns the newly added employee</response> 
        /// <response code="400">If the posted employee is null</response>
        [HttpPost]
        [ProducesResponseType(StatusCodes.Status201Created)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        [ProducesDefaultResponseType]
        public IActionResult Post([FromBody] Employee employee)
        {
            employees.Add(employee);
            return CreatedAtAction(nameof(Get), new { employee.Id }, employee);
        }

 

Then run the app again and see the changes in the post employees endpoint.

ASP.NET Swagger

 

Swagger Code Generation

Swagger can help with client-side code generation by providing a code generation tool that automatically generates client-side code based on the OpenAPI Specification of the API. This tool is often called a Swagger codegen tool, and it can generate client code in a variety of programming languages, such as Java, Python, C#, and JavaScript.

The Swagger codegen tool uses the OpenAPI Specification to generate client code that is consistent with the API definition, ensuring that the client code is up-to-date with any changes made to the API. This can save developers a significant amount of time and effort, as they don’t need to manually create client-side code that interacts with the API.

By providing a standardized format for describing APIs, Swagger makes it easier for developers to generate client-side code that is compatible with a wide range of programming languages and frameworks. This can help to reduce the learning curve for developers who are new to the API, and make it easier for them to integrate the API into their own projects. More on Swagger code generation is outside of the scope of this article. To learn more about that, check out our powerful ASP.NET full-stack web development course that also Test-Driven development. During the course we create an end-to-end Flight Booking portal using ASP.NET and Angular and use Swagger code generation in action to generate the client code that interacts with the API.

ASP.NET Swagger Summary

In this article, we’ve walked through the process of configuring Swagger in an ASP.NET Web API application using .NET 7.0. We’ve also created a simple CRUD controller for managing employees, and tested the API using the Swagger UI. With Swagger, we can easily document and test our web services, making it easier for developers to understand and use our APIs.