Spring Boot and Swagger — Writing Good API Documentations | by Farzin Pashaee | Jun, 2022

Documentations made easy

APIs are one of the key players in the technology world whether they are used in a simple mobile application in integrating complex enterprise systems. Any application can become a platform by enabling methods to enhance and add services to existing products using APIs.

Having good documentation for these APIs is critical to their success. API documentation is technical content that includes instructions on using and integrating the APIs. Think of it as a reference manual with all of the information you need to work with the API, like the request and response format, and how to start working with them.

You can always have your format of documentation for your APIs, but having a standard or a common format will make it more readable. Using good practices like Spec-driven development (SDD) also can help in keeping effective documentation. There are several specifications to get started with documenting, such as RAML (RESTful API Modeling Language), OpenAPI (formerly Swagger), and API Blueprint, but in this article, we will focus on OpenAPI and Swagger for Spring Boot Applications.

Swagger is a set of open-source tools that help you to describe REST-based APIs. This gives you the luxury to automatically build beautiful and interactive API documentation, automatically generate client libraries for your API in many languages, and explore other possibilities like automated testing.

To begin working with OpenAPI and creating your first swagger document you will need the following dependency in your application.

<dependency>     
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>

Having version 3.0.0 of the starter make sure you have the compatible version of the starter parent dependency. in my case, I am using 2.4.0.

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.0</version>
</parent>

Now having these dependencies all in place you need to provide the Docket bean to start serving the open API documentation endpoint. To do that you can add the following configuration with the given method with @Bean annotation.

@Configuration
public class SwaggerConfig{
@Bean
public Docket getDocket() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build();
}
}

The select() method will return ApiSelectorBuilder which can be used to manage the exposed swagger endpoints. In case you want the documentation for a specific path or package you can change the input for the related methods.

return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("fp.sw.controller"))
.paths(PathSelectors.regex("/student/*"))
.build();

in our case, we used any() which will result in documenting all APIs. After preparing The Docket bean and running the application you can get the machine-readable version of the APIs documents in JSON format using the following endpoint.

http://localhost:8080/v2/api-docs

Now to have a human-readable version and some extra features for testing we can use the swagger-UI dependency. The only thing you need to do to have it is to add the following dependency in your POM file.

<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>3.0.0</version>
</dependency>

If you run your application after adding this dependency and visit the URL below, you will find a web-based GUI that describes the API and gives you the functionality to test your APIs.

http://localhost:8080/swagger-ui/

On this page by default and based on your Docket configuration you will see a list of controllers. If you extend the controller you will find a list of valid methods (GET, POST, PUT, DELETE, HEAD, OPTIONS) as you defined inside the controller. By extending each method you will the useful data about the parameters list, content type, response status, and ..

Documentation with Annotations

To have some more details about each method, parameters, and the rest of the involved entities you can use a set of annotations to add comments which will later be rendered in the UI by swagger. Here are some of the most used annotations for documenting the APIs via swagger:

@ApiOperation — using this annotation on the method you can add some description for that method and it will appear next to the path of the endpoint in the swagger UI.

@GetMapping("/{id}")
@ApiOperation(value="Getting student user information")
public ResponseEntity<Student> getStudent(
...
@ApiOperation annotation in swagger-UI

@ApiParam— This annotation will be used to describe the parameters in the requested method.

@GetMapping("/{id}")
public
ResponseEntity<Student> getStudent(
@ApiParam(value = "Student ID number" , required = true , example = "1")
@PathVariable Long id ){
...
@GetMapping annotation in swagger-UI

@ApiModelProperty — can be used to describe properties in the model which are used as a request or response object.

public class Student {
@ApiModelProperty(notes = "Student Id Number",
example = "1", position = 1)
private Long id;

@ApiModelProperty(notes = "Student name",
example = "John", position = 2)
private String name;
}

@ApiModelProperty annotation in swagger-UI

You can find the complete list here.

Securing Swagger

Because you are exposing some sensitive information via swagger it is recommended to disable the swagger in the production environment or at least secure it. To secure it you can use Spring Security and add the related started and by default, the swagger endpoints will be secured with basic authentication methods. You have a lot of flexible options in Spring Security for authentication and authorization which you can utilize.

Generate Client Libraries

Another benefit of using swagger is that you can use the OpenAPI Swagger spec to generate client libraries or SDKs in different languages. Swagger Codegen is one of the tools that can be used to create these libraries. Swagger Codegen can simplify your build process by generating server stubs and client SDKs for any API, defined with the OpenAPI (formerly known as Swagger) specification, so your team can focus better on your API’s implementation and adoption. While the tool quickly generates client libraries in 40 different languages, it also integrates with SwaggerHub. This makes collaboration much easier via the tool’s cloud interface.

Automated Testing

Having a machine-readable Swagger spec of your APIs gives you the possibility to use other applications to prepare the automated tests. Tools like Assertible and Postman can be used to import the Swagger spec and automatically create tests and assertions for every endpoint and method.

Leave a Comment