Tech Insights
Indika Karunarathna
July 13, 2021

RESTful Web API Experience with Swagger UI

RESTful Web API Experience with Swagger UI

API (Application Programming Interface) is an integral part of Software Development, and therole of the software developer spans from developing own APIs to consuming theAPIs, which are developed by the other developers. Since all the softwaredevelopers may not get involved in every activity related to API development,there should be proper documentation on API that can be read and understood by any software developer at any given time. This is why API Documentation playsan important role in API development.

API Documentation

API Documentation is atechnical content deliverable, containing instructions about how to effectivelyuse and integrate with an API. This contains all the information required towork with the API, such as what it does and how to use it, with details aboutfunctions, classes, return types, argument, etc.

Why do we need APIDocumentation?

API Documentation is amust in API development since without that there is no way to know about theAPI beforehand; matters such as purpose, operations, arguments, return values,exceptions that should be handled by the consumer, etc.

So, the API Documentation mostly ease the work of the developer by providing the essentials of the API including above characteristics as well as how to use, test anddeploy the API faster and effectively. It also reduces the learning curve forthe developer.

OpenAPI Specification (OAS)

OpenAPI Specification isan API description format for RESTful web APIs. It defines a standard,language-agnostic interface to RESTful APIs, which allows both humans andcomputers to discover and understand the capabilities of the service without accessing the source code. An OpenAPI file describes the entire API, including:

1.      Available endpoints and operations of each endpoint.

2.     Input andoutput parameters of each endpoint.

3.     Authentication methods.

4.     Contact information, license, terms of use and other information.

API Specification can bewritten in YAML or JSON. The format is easy to learn and readable by both humans and machines.

Swagger

Swagger is an Open-source API Documentation framework, or a set of Open-source tools build around the Open API Specification to help developers to design, build, document,and consume RESTful web APIs.

The major Swagger tools include:

Swagger Editor

Swagger Editor is anOpen-source editor to design, define and document RESTful APIs in the Open API Specification. Swagger Editor is a way to create and edit the Swagger file inthe YAML format.

Swagger UI

Comprehensive walk through of the Swagger UI is carried out in the rest of this document withan example of generating the Swagger file and displaying it in Swagger UI.

Swagger Codegen

Swagger Codegen is anOpen-source project, which allows generation of API client libraries, serverstubs, and documentation automatically from an OpenAPI Specification or the Swagger file. Once the server stubs are generated, developer can only focus onthe business logic. Swagger Codegen can be used to generate both API client libraries and server stubs in numerous languages.

Swagger UI

·        Swagger reads an API and extracts it in the form of an interactive UI called SwaggerUI.

·        Swagger UIoffers HTML view of API with JSON support, which can be used easily to test the end points.

Swagger UI allows anyoneto visualise and interact with the API resources without having any of theimplementation logic in place. It is automatically generated from the OpenAPISpecification, with the visual documentation making it easy for back-endimplementation and client-side consumption.

Most important fact about the Swagger UI is that it only exposes the essentials of the API thatonly required to be known by the consumers who use the API. The logic behindthe API is always hidden to the consumers, and they always consume or test theactual API endpoint using the Swagger UI. So, the time taken to execute theoperation, and the response of the endpoint is the original, unless there is atest endpoint to simulate the operation using test data targeting a different testing environment.

Postman and the Benefits ofusing Swagger UI over Postman

Postman is acollaboration platform for API Development, which is used by the software developers. Postman is also a scalable API testing tool widely used. But therecan be numerous advantages, we can achieve by using Swagger UI over Postman.

Once Swagger UI is configured in the target platform, each endpoint is automatically captured, andUI is generated for all the end points. There is no need for setting up eachendpoint manually.

After any modificationin API, the modification is captured when generating the Swagger file, andreflects in the Swagger UI. On the other hand, in Postman, we must do the necessary changes manually when accessing and testing the API.

Swagger UI describes theAPI properly with all the Request, Response and Schema information attached. Byreferencing them, the API can be easily understood by the developers.

However, Postman has afeature to support the Swagger file integration if the Swagger file isavailable. By importing the Swagger file, all the end points will be availablefor testing in Postman.

To get these benefits,developer needs to setup the Swagger in the target platform. Configuring Swagger is the only extra effort a developer has to put.

Though there are these benefits that can be achieved by using Swagger UI, it is not a total replacement of the Postman, comparing with all the features available withPostman.

Creating the Swagger File in C#

Swagger can be used withdifferent technologies such as,

·        Spring boot

·        Node JS

·        ASP.Net WebAPI

·        Etc.

To describe the featuresof Swagger, and to show the convenience of using Swagger, below sectiondescribes how the Swagger is set up with ASP.Net Web API and how the Swagger UIwill look like at the end.

First of all, we need tocreate an ASP.Net Core Web API project, and here I have used Visual Studio 2019Community edition.

Then, we must install aset of NuGet packages, which are used to generate the Swagger UI based on theAPI definitions in the project. The list of NuGet packages need to be installedfor this purpose are shown in the Figure 1.

Figure 1: The main NuGet packages required to generate theSwagger file.

Next step is to add theSwagger configurations into the Web API project. These configurations need tobe added to the Startup.cs file available in the root of the ASP.NetCore Web API project. Services must be added to the container, and the HTTPrequest pipeline must be configured to complete the configuration process.

To register the Swaggergenerator, which contains one or more swagger documents, we need to modify the ConfigureServices(IServiceCollectionservices) method as shown in the Figure 2.

Figure 2: Registering the swagger generator.

As of the code sample inFigure 2, there are three Swagger documents defined with the keys adminV2,adminV1 and publicV1. These keys are used to explore the APIs inside thecontrollers and show them in the Swagger UI.

As the code depicts, wecan add Security definitions, if we also need to authorise when accessing theAPI.

To configure the HTTPrequest pipeline, basic configurations, which are highlighted in the Figure 3,need to be added inside the Configure(IApplicationBuilder app,IWebHostEnvironment env) method.

Figure 3: Configure the HTTP request pipeline.

There are three SwaggerJSON endpoints defined, which are mapped to three Swagger documents defined inthe ConfigureServices method.

Then we can add theattributes to the APIs, to map the APIs to the Swagger endpoints.

The code sample in Figure 4 contains EmployeeController that maps to the Swagger endpoint adminV2. Thecontroller contains one HttpPost endpoint that is used to insert anEmployee to the database. The attributes that should be mapped to the Swaggerdocument are defined in the SwaggerOperation attribute of the endpoint.

Figure 4: Implement the Controller and add Swagger Attributes.

Finally, once theservices are hosted after all the endpoints are implemented, we can access theSwagger UI by the URL.

              [Service_Host]/swagger/index.html

We can select thedefined Swagger document as displayed in the Figure 5. Also, the Title with theVersion are displayed in the UI accordingly. Endpoints are grouped by the valueof the Tags parameter in the SwaggerOperation attribute defined.

Figure 5: Final Swagger UI output.

Content of the swagger.jsonfile of the above API Documentation can be viewed by clicking the URL,

[Service_Host]/swagger/adminV2/swagger.json

Each endpoint is quitedescriptive and ready to be tested. For an example, if we select AddEmployee endpoint, it will look like in the Figure 6. By clicking Try itout button, we can edit the request body and submit the request. Once theAPI is executed, then the response body of the API response is displayed withthe response status on the Swagger UI.

Figure 6:Representation of an endpoint on the Swagger UI.

The above ASP.Net WebAPI code sample is a brief example to generate the Swagger UI output availablein the Figures 5 and 6. As of the complexity and the content of the API, C#code can be extended further based on the requirements.

The main objective ofthis document is to explain the importance of having API Documentation, andautomating the process of generating the API Documentation, which complies the OpenAPISpecification using Swagger UI.

Following resources canbe further used to learn and extend the knowledge of the OpenAPI Specificationand Swagger.

OpenAPI Specification: https://swagger.io/specification/

Swagger: https://swagger.io/

Swagger Editor: https://swagger.io/docs/open-source-tools/swagger-editor/

Swagger UI: https://swagger.io/tools/swagger-ui/

Swagger Codegen: https://github.com/swagger-api/swagger-codegen

As mentioned in thisdocument, Swagger UI can be integrated to not only with ASP.Net Core Web API,but also with other technologies like Spring Boot and Node.js as well.Generating Swagger UI using your preferred language and exploring the features,is a simple task for you.