Documenting API's Using Swagger

Introduction

Before discussing Swagger, I will go through how to describe a web API using it in this article. Let's discuss open APIs.

Open API

Open API is a specification that helps describe the capabilities of a rest API, such as:

  • Available endpoints
  • Operating Parameters
  • Authentication Methods
  • Contact information, license, terms of use, and other information

Why use OpenAPI for API documentation

OAS(OpenAPI Specification) outlines an API's contract so that all parties involved—including your development team and end consumers—can interact with the API's resources without incorporating them into their applications. This contract can be parsed and understood by robots and people since it is human-readable and language-independent.

Without mentioning code implementation, the OAS contract states what the API does, its request parameters, and response objects.

Swagger

Swagger is a set of tools that helps implement the OpenAPI specification; one of the tools is the Swagger UI, which can render the documentation in the browser.

  • Swagger Editor
  • Swagger UI
  • Swagger Codegen 

Note- will use Swashbuckle, an open-source.NET implementation of the open API.

Install and Configure Swagger

Let's install the Swashbuckle NuGet package. The name of the package is swashbuckle.asp.net core.

Documenting API's using swagger

Once the package is installed, we need to configure the Swagger middleware. Let's edit the Program.cs file. We invoke the method AddSwaggerGen on the service collection. In the configuration option, we use Swaggerdoc to define one Swagger document, which has v1 as the name and the title set to Api.

Let's jump into the configure method. We invoke the method using Swagger on the application builder object; then, we invoke the method using Swagger UI. We will enable Swagger UI, exposing the documentation in the browser.

Documenting API's using swagger

Before testing in the browser, let's edit the lunchsetting.json file, we set the launch browser property to True so that the browser is launched when the server runs, and we set the launch URL to empty because I want Swagger UI to serve at the application root and make it possible. I also need to update the UseSwaggerUI call in the configure method, so I set the property route prefix to an empty string. Swagger is now configured.

Documenting API's using swagger

Enhance Swagger Documentation with Data Annotation

Let's run the app; as you can see, we now have a page with documentation. We can enhance the documentation by adding XML comments to our code.

Documenting API's using swagger

Look at the Get endpoint; there is a description now, and if I expand it, there is also a sample request. This information comes from the content of the XML comment.

Documenting API's using swagger

/// <summary>
/// Get book detail
/// </summary>
/// <param name="bookId"></param>
/// <returns></returns>
[HttpGet]
[Route("GetBookDetail")]

public async Task<IActionResult> GetBookDetail(int bookId)
{
    book objbook= new book();
    try
    {
        objbook = await _library.GetBookDetail(bookId);
    }
    catch (Exception ex)
    {
        return BadRequest(ex.Message);
    }
    return Ok(objbook);
}

Let's add some comments for the post endpoint in the controller. I can add a summary; this method is a parameter and can also describe it. Let's see the result displayed in summary. If I expand the method, I will have an explanation for the request body. XML comments are not the only way to enhance the documentation. We can use data annotations on the controller or an action method. The get endpoint returns data as JSON; this is not explicitly stated in the documentation.

/// <summary>
/// Adding member
/// </summary>
/// <param name="addmember"></param>
/// <returns></returns>
[HttpPost]
[Route("AddMember")]

public async Task<IActionResult> AddMember(Member addmember)
{
    int result = 0;
    try
    {
        result = await _library.AddMember(addmember);
        if (result == 1)
        {
            return Ok("Values are inserted");
        }
        else
        {
            return BadRequest("Something went wrong");
        }
    }
    catch (Exception ex)
    {
        result = 0;
        return BadRequest(ex.Message);
    }
}

Documenting API's using swagger

Besides providing documentation, Swagger UI allows us to test an endpoint. I can click on the Try It Out button and execute the request. As you may have noticed, I get a 200 status code, which is a successful response.

Documenting API's using swagger

Conclusion

It is advantageous for a developer and the project they are working on to use Swagger for API implementation. It enables the simulation of any development methodology and offers an easily testable API. Moreover, Swaggers are useful resources for API documentation.

To summarise, Swagger enables machines and developers to grasp REST APIs capabilities without relying on source code interpretation. The amount of work needed to align and describe disconnected services is decreased using REST APIs.

Thanks for reading this article. I hope this helped you to grasp the topic of documenting APIs using Swagger.


Similar Articles