OpenAPI Specification — Swagger UI

Sourabh Parsekar
Nerd For Tech
Published in
9 min readOct 31, 2020

--

What is an API and why do you need one? It’s old but still holds… https://www.govtech.com/applications/Whats-an-API-and-Why-Do-You-Need-One.html

We, the developers, tend to use an existing piece of code(mostly from stackoverflow.com), rather than re-inventing the wheel.

APIs are driving a new wave of innovation centered on sharing services without the developer having to share his code. APIs are thus a reusable component in the sense, they implement a piece of a puzzle that others can reuse without having to resolve the same puzzle piece. That’s why we often hear people say “Can’t you just use an API for that?”. Google currently offers more than two dozen APIs, which can be found on the Google Code site

One can say, Application Programming Interface (API), allows other programs to interact with it, without the need for a developer to share the entire code. The developer exposes an API that tells a programmer how they can interact with the existing service. This points out the need for a standardized way of documenting an API which would help other programmers to understand and use API efficiently.

In this article, we are going to see how to simplify and standardize our API documentation using open API specification and rendering a swagger UI.

Github Code — Here’s the link to the code that we will use throughout this article. Feel free to clone it, try it, share it, improve it and most importantly use it to simplify your API documentation.

Remember that, Poor or Non-Existent Documentation is one of the reasons why your API is not being used by others.

What is Open API Specification (OAS)?

https://swagger.io/

The OpenAPI Specification(OAS) was earlier known as the Swagger Specification. It is a standard for defining RESTful interfaces. When OAS is properly defined, a consumer can understand and interact with the remote service with a minimal amount of implementation logic.

The OpenAPI Specification (OAS) defines a standard, language-agnostic interface to RESTful APIs which allows both humans and computers to discover and understand the capabilities of the service without access to source code, documentation, or through network traffic inspection.

What is Swagger UI?

https://swagger.io/

Swagger, first released in 2011, is an online interactive HTML documentation page that defines and describes RESTful APIs and is expressed using JSON. Thus, Swagger UI generates interactive API documentation that lets consumers try out the API calls directly in the browser by interacting with the live APIs.

OAS would be incomplete without talking about Swagger UI.

An OpenAPI definition uses and conforms to the OpenAPI Specification. The original foundation of the OAS was the Swagger project from SmartBear, consisting of the Swagger Specification and the Swagger tools. Swagger is one of the most widely used open-source toolsets for developing APIs with the OpenAPI Specification.

Let’s look at the code implementation

Now that we have seen the theoretical advantages, let’s looks at how we could integrate this into our projects. For this example, I am using SpringBoot - 2.3.4.RELEASE, Apache Maven as build tool and Java 8. The full demo project code is available on GitHub. Refer to the README.md file to set up and run the project on your local.

What is our end goal?

We would go step by step to understand how to code and implement the Swagger UI using OpenAPI Specification.

We would also see how to use it to test our services.

Once we are done, do try it out yourself using the sample code.

So let the game begin …

Step 1: OpenAPI Specification Maven Dependency

In the Swagger2 version, we had to import 2 Springfox Swagger Jars to set up the Swagger UI. When moving to Swagger 3, we have only one dependency to be used. The latest version of springdoc-openapi-uican be found on Maven Central. To add it to our Maven project, we need to add the dependency in the pom.xml

OpenAPI Specification dependency

Step 2: Swagger Configuration with SpringBoot

The configuration of Swagger3 requires the OpenAPI bean. License and Contact information can also be added using OpenAPI bean. For the sake of simplicity, title, version, and description is being taken from `application.properties`

Once we get our configuration setup, it’s time to add API endpoints with Swagger annotations which are described in further steps.

Step 3: Let’s add our first endpoint for POST request

We will be using SpringBoot Rest APIs for this demo. We will go through all the annotations used in the sample code. This includes Spring Annotations and Swagger annotations. Since this is just an introduction, we would not be seeing details for each annotation, but we would cover the few annotations that can help us with neat documentation. Now, let’s look at HTTP POST

Spring Annotations

RestController annotation indicates that the data returned by each method will be written straight into the response body instead of rendering a template.

PostMapping annotation maps HTTP POST requests onto specific handler methods. It is a composed annotation that acts as a shortcut for RequestMapping(method = RequestMethod.POST).

RequestBody annotation indicates a method parameter should be bound to the body of the web request.

Swagger Annotations

Operationannotation may be used to define a resource method as an OpenAPI Operation, and/or to define additional properties for the Operation. I have used to describe the operation.

ApiResponses is a container for repeatable ApiResponse annotation.

ApiResponse annotation may be used at the method level or as a field of Operation to define one or more responses of the Operation.

Contentannotation may be used to define the content/media type of a parameter, request or response, by defining it as a field Parameter.content(), RequestBody.content() or ApiResponse.content()

Schema annotation may be used to define a Schema for a set of elements of the OpenAPI spec, and/or to define additional properties for the schema. It applies e.g. to parameters, schema classes (aka “models”), properties of such models, request and response content, header.

Swagger Annotations are optional and it can create minimal Swagger UI with Spring Annotations. However, with Swagger annotations, we can make the documentation more readable and user friendly.

Let’s go through the sample code and swagger output below. Swagger creates a ready to use sample request/response and also has a ‘Try it out’ option which can be used to test the live API. We will check out the ‘Try it out’ option in later sections.

Sample Controller Endpoint for the HTTP POST request
Swagger for the HTTP POST request

Step 4: Let’s add our endpoints for GET request

As some of the annotations are already covered in HTTP POST above, we will go through the annotations that are new for our HTTP GET request. For GET, we will see get all employees and get an employee by id.

Spring Annotations

GetMapping annotation for mapping HTTP GET requests onto specific handler methods. It is a composed annotation that acts as a shortcut for RequestMapping(method = RequestMethod.GET).

PathVariable annotation indicates that a method parameter should be bound to a URI template variable. This is generally used when we need to find something by id.

Swagger Annotations

Parameterannotation can be used on a method parameter to define it as a parameter for the operation, and/or to define additional properties for the Parameter. This is generally used when we need to find something by id.

Let’s go through the sample code and swagger output below.

Sample Controller Endpoint for the HTTP GET all request & HTTP GET by id request
Swagger for the HTTP GET all request
Swagger for the HTTP GET by id request

Step 5: Let’s add our endpoint for PUT request

As some of the annotations are already covered in the HTTP POST, GET above, we will go through the annotations that are new for our HTTP PUT request. A slight variation I have done here is that if the employee does not exist then create a new employee. So the response can either be 200 for an update or 201 for adding a new employee.

Spring Annotations

PutMapping annotation for mapping HTTP PUT requests onto specific handler methods. It is a composed annotation that acts as a shortcut for RequestMapping(method = RequestMethod.PUT).

Let’s go through the sample code and swagger output below.

Sample Controller Endpoint for the HTTP PUT request
Swagger for the HTTP PUT request

Step 6: Let’s add our endpoint for DELETE request

As some of the annotations are already covered in the HTTP POST, GET, PUT above, we will go through the annotations that are new for our HTTP DELETE request. A slight variation I have done here is that if the employee does not exist then return 400 Bad Request else return the deleted employee. Generally, you do not respond with the deleted entity and the status code is 204 No Content to indicate the deletion was a success.

Spring Annotations

DeleteMapping annotation for mapping HTTP DELETE requests onto specific handler methods. It is a composed annotation that acts as a shortcut for RequestMapping(method = RequestMethod.DELETE).

Let’s go through the sample code and swagger output below.

Sample Controller Endpoint for the HTTP DELETE request
Swagger for the HTTP DELETE request

Step 7: Voila. We are done!! Let’s test

Swagger “Try it out”

If you have downloaded the sample code on your local machine, compiled it, and run it, you would have already loaded the Swagger UI in your favorite browser.

To run the swagger, after you run the SpringBoot application, you can hit the URL:

http://localhost:10001/open-api-demo/swagger-ui.html

As a guide to you to download the code and/or compile it and/or run it, refer to the README.md file in the sample code root directory. If you are still not able to make it work, drop me a comment or a note. We can dig in together to make it work. Afterall, getting your hands dirty will help you understand it easily.

Assuming you have done everything with the sample code, we have no other configuration left before we try out the API. Swagger has a built-in “Try it out” button against each API, which has the capability to run request so that the consumer can verify the output. It also shows the request that was sent along with the headers and other parameters.

Thus, when you try to execute a request, Swagger will read the definition of the request and expect the consumer to provide the test data if applicable, such as a path parameter or a request body. Once data is input, the consumer can hit Executewhich runs the request and its response is shown.

While we talk about all this, there are disadvantages of running Tests with Swagger due to its limited verification functionalities. It is up to the user to verify if it’s the expected response. Additionally, requests have to be run one at a time, due to the lack of built-in automation functions.

Let’s see the ‘add new employee’ success request in action while you can try the other request on your system.

Try it out for HTTP POST request

We have now successfully added Swagger and tested our APIs. Having said that, it brings us to the end of our exploration of API Documentation. In our journey, we have seen how to add Swagger UI for API Documentation using OpenAPI Specification and Swagger 3.

To summarise our journey, we have created a SpringBoot application with Rest Controller. We added Swagger dependency and the necessary OpenAPI Specification configuration. Further, to configure Swagger to display meaningful API documentation, we have used Swagger annotations in addition to Spring annotations. However, we have not seen everything about Swagger, and it’s your time to explore the other capabilities. I will however have another blog on how to secure the APIs using the JWT token.

--

--

Sourabh Parsekar
Nerd For Tech

Just another developer... Java | Spring-boot | Blockchain