Documentation of REST APIs

Need for documenting your REST APIs

We need to implement one more standard which is documenting all our REST APIs that we have developed so far.

Here you may have a question like why should I document my own REST APIs?

→ As soon as you start exposing your REST APIs and microservices for external agencies or to some other team inside your organization, who are supposed to consume your microservices or REST APIs.

Think like there is an UI team or there is a mobile application team. They want to consume your backend logic with the help of your REST APIs or microservice. These kind of scenarios, they will have many, many questions.

The questions are like : 

  • What is the request format that you are going to accept? 
  • What is the response format that they are going to receive?
  • What are the validations that you have enforced inside your REST APIs?

To some extent you can answer these questions by scheduling a meeting, and inside the meeting you can discuss everything about your REST APIs and you think you are good with that.

But in the long run, think about the pain process that you have to go through, if more and more third party applications (or) more and more other developers are trying to consume your REST APIs.

This will make your life tough and you need to repeat and share this information every time someone asks you. Instead, it will be a good idea to document our REST APIs by following a industry standard.

How do document

Specs – https://www.openapis.org/

The standards that we need to follow here is Open API specification.

Open API is an open source community, who maintain how to document our Http APIs like REST APIs, that provides a standardized means to define your API to others.

So whoever is trying to consume your REST APIs or whoever is trying to test your REST APIs, they can quickly discover how an API works, they can configure infrastructure, they can also generate client code, server code and create test cases from your APIs quickly whenever you document your REST APIs by using these open API specification.

Adding springdoc-openapi dependency

We will use the library → springdoc-openapi

Check this — https://springdoc.org/

You can simply add a maven dependency into your spring boot web application or microservice web application.

  <dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>2.4.0</version>
</dependency>

Behind the scenes, it is going to scan all your REST APIs and prepare the documentation for your REST APIs based upon the open API specification.

It is also going to provide you an swagger UI using which anyone can understand your REST APIs, the details about your REST APIs and the validations that you have enforced everything.

NOTE – this dependency is going to work only if you are using a Spring Boot version which is >= to 3.0.

Opening Swagger UI

After adding this dependency, just rebuild the application and you see the magic.

I’m trying to open a path which is localhost:8080/swagger-ui/index.html

In the schema section, you can see all the request and response objects that your REST API is going to use inside a microservice.

Professional touch to your REST API documentation

Let us go step by step targeting each section of the Swagger UI.

@OpenAPIDefinition annotation

This section : 

As of now, this section does not have any much information about what is the purpose of my REST APIs that I’m trying to expose here.

  • What is the summary?
  • What is the description?
  • Is there any contact information?
  • Is there any licensing information?

Let’s try to document these details with the help of few annotations that we have.

Go to the Spring Boot main application class – AccountsApplication.

We are trying to provide the definition details with the help of Open API. We use the @OpenAPIDefinition annotation.

Using this annotation we need to invoke a param which is info and to this info param we should again invoke an annotation which is @Info.

Using this annotation I can populate what is the title of my spring boot documentation.

After this title, we can also mention the description.

I can also mention contact param using an annotation @Contact.

License details we can mention using @License annotation.

@SpringBootApplication
@EnableJpaAuditing(auditorAwareRef = "auditAwareImpl")
@OpenAPIDefinition(
info = @Info(
title = "Accounts microservice REST API Documentation",
description = "Accounts microservice REST API Documentation",
version = "v1",
contact = @Contact(
name = "Raghunath D",
email = "mail@rndayala.com",
url = "https://www.rndayala.com"
),
license = @License(
name = "Apache 2.0",
url = "https://www.rndayala.com"
)
),
externalDocs = @ExternalDocumentation(
description = "Accounts microservice REST API Documentation",
url = "https://www.rndayala.com/swagger-ui.html"
)
)
public class AccountsApplication {
public static void main(String[] args) {
SpringApplication.run(AccountsApplication.class, args);
}
}

Output : 

Provide info for the controller

@Tag annotation

In order to provide some information which is specific to all the APIs present inside the controller class, we need to use an annotation which is @Tag.

Changed from : 

To : 

Provide info at each REST API level

  • What is this API supposed to do?
  • What is the summary?
  • What is the description?

@Operation annotation

We need to provide summary and description to this API level annotation.

Example —

@Operation(
summary = "Create Account REST API",
description = "REST API to create new Customer & Account"
)
@PostMapping("/create")
public ResponseEntity<ResponseDto> createAccount(
@Valid @RequestBody CustomerDto customerDto)
{
service.createAccount(customerDto);
ResponseDto responseDto = new ResponseDto(
AccountsConstants.STATUS_201,
AccountsConstants.MESSAGE_201);


return new ResponseEntity<>(responseDto, HttpStatus.CREATED);
}

Output : 

Providing API Response documentation

@ApiResponses and @ApiResponse annotation

Example —

@Operation(
summary = "Create Account REST API",
description = "REST API to create new Customer & Account"
)
@ApiResponses({
@ApiResponse(
responseCode = "201",
description = "HTTP Status CREATED"
),
@ApiResponse(
responseCode = "500",
description = "HTTP Status Internal Server Error",
content = @Content(
schema = @Schema(
implementation = ErrorResponseDto.class
)
)
)
}
)
@PostMapping("/create")
public ResponseEntity<ResponseDto> createAccount(
@Valid @RequestBody CustomerDto customerDto)
{
service.createAccount(customerDto);
ResponseDto responseDto = new ResponseDto(
AccountsConstants.STATUS_201,
AccountsConstants.MESSAGE_201);
return new ResponseEntity<>(responseDto, HttpStatus.CREATED);
}

Now under REST API responses you see something like this : 

@Schema annotation

Currently the DTO classes are looking like this : 

We are showing the technical/class names directly. How can we add documentation to them?

The @Schema annotation is part of the Swagger API documentation and code generation tool for RESTful web services. It’s used in Java applications, specifically with frameworks like Spring Boot, to provide additional metadata and documentation about API models (DTOs – Data Transfer Objects) and their properties.

The @Schema annotation allows you to describe the model (class) and its properties (fields) in your Java code. This includes specifying the model’s name, description, and additional details about each property.

You can use @Schema to define fields/properties such as their name, type, format, description, default value, required status, example values, and more. This information is crucial for generating accurate API documentation.

Example the class will look like this –

@Data
@NoArgsConstructor
@AllArgsConstructor
@Schema(
name = "Customer",
description = "Schema to hold Customer and Account information"
)
public class CustomerDto {
@Schema(
description = "Name of the customer", example = "Eazy Bytes"
)
@NotEmpty(message = "Name can not be a null or empty")
@Size(min = 5, max = 30, message = "The length should be between 5 and 30")
private String name;

@Schema(
description = "Email of the customer", example = "tutor@eazybytes.com"
)
@NotEmpty(message = "Email address can not be a null or empty")
@Email(message = "Email address should be a valid value")
private String email;

@Schema(
description = "Mobile Number of the customer", example = "9345432123"
)
@Pattern(regexp = "(^$|[0-9]{10})", message = "Mobile number be 10 digits")
private String mobileNumber;
private AccountsDto accountsDto;
}

By using @Schema annotations in your Java code, you can enhance the clarity, accuracy, and completeness of your API documentation, making it easier for developers to understand and use your RESTful APIs.

Output :