Documenting a Spring REST API Using OpenAPI and Swagger-UI

Documenting a Spring REST API Using OpenAPI and Swagger-UI

Hello World !!

In my previous blogs, we have seen how to develop REST CRUD APIs using Spring Boot and MongoDB.

  • Spring Boot + MongoDB : Pagination APIs - Click Link

    • In this blog, we have created some APIs to get data from database using pagination.
  • Spring Boot + MongoDB : CURD APIs - Click Link

    • In this blog, we have created some APIs like create, update, delete and get data from database.

Overview

In today's development, there are so many things connected with APIs and this APIs are really helpful if we are dealing with multiple platform apps and multiple system together.

This kind of APIs needs to be documented properly so as and when required any developer can take a better look at this APIs and use this in very efficient way.

Documentation is an essential part of building any REST APIs.

In this blog, we’ll look at SpringDoc, which simplifies the generation and maintenance of API docs based on the OpenAPI specification for Spring Boot applications.

Technology

  • Java

  • Spring Boot

  • MongoDB

  • Maven

Project Structure

Till now, we have created project and some basic APIs developed. If you need to re-visit that topics please follow the link mentioned above.

Now, we are going to modify our code and going to add new dependency related to SpringDoc and OpenAPI.

New Dependency

Spring Boot 3.x requires to use version 2 of springdoc-openapi.

<!-- https://mvnrepository.com/artifact/org.springdoc/springdoc-openapi-starter-webmvc-ui -->
<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
    <version>2.3.0</version>
</dependency>

OpenAPI Description Path

After adding the dependency correctly, we can run our application and find the OpenAPI descriptions at /v3/api-docs, which is the default path:

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

Further, we can customize the path in application.properties using the springdoc.api-docs property. For example, we can set the path to /api-document:

springdoc.api-docs.path=/api-document

Then, we’ll be able to access the docs at:

http://localhost:8080/api-document

By default, OpenAPI API Document are in JSON format, For yaml format, we can obtain the generated doc at:

http://localhost:8080/api-document.yaml

Swagger UI

The springdoc-openapi library also supports swagger-ui properties. These can be used as Spring Boot properties with the prefix springdoc.swagger-ui.

For example, we can customize the path of our API documentation by changing the springdoc.swagger-ui.path property inside our application.properties file:

springdoc.swagger-ui.path=/api-document.html

So, now our API documentation with Swagger-UI will be available at http://localhost:8080/swagger-ui/index.html this url.

Generate Documentation Using Operation and ApiResponses

To add some kind of description to our API, we can use couple of annotations.

We are going to use Operations and ApiResposnes annotations.

@Operation(summary = "Get a User by its id")
    @ApiResponses(value = {@ApiResponse(responseCode = "200", description = "Found the User", content = {@Content(mediaType = "application/json", schema = @Schema(implementation = User.class))}), @ApiResponse(responseCode = "400", description = "Invalid id supplied", content = @Content), @ApiResponse(responseCode = "404", description = "User not found", content = @Content)})
    @GetMapping(value = "/getUser", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<UserResponse> getUserById(@RequestParam BigInteger id) {

        try {
            return new ResponseEntity<UserResponse>(new UserResponse(HttpStatus.OK.value(), "Success", userService.getUserById(id)), HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<UserResponse>(new UserResponse(HttpStatus.INTERNAL_SERVER_ERROR.value(), "Failure", "Not Able To Get User By Id,Please Try After Some Time"), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

Here, now you can see the difference in document,

Disable SpringDoc : API Document

By default, once the dependency is added, SpringDoc is enable but as per environment and requirements we can disable this using properties mentioned below,

springdoc.api-docs.enabled=false

Now, you can't access JSON/YAML or Swagger-UI Document as it's disabled.

Disable Swagger-UI

As we have disabled SpringDoc, we can also disable specific to Swagger-UI only too.

In order to disable Swagger-UI only, we need to use below mentioned properties,

springdoc.swagger-ui.enabled=false

Now, our Swagger-UI is disabled but our JSON/YAML API Doc is enabled.

Package Scan

By default, SpringDoc will scan all the packages available in project to generate this document. But, also we can manage and declare what package needs to scan during doc generation using below properties,

springdoc.packages-to-scan=package1,package2

We can mentioned multiple packages to scan using comma separated values too.

Important Links

Over here, we have seen some limited annotations and properties related to SpringDoc and Swagger-UI, You can visit below links for better and in-detail understanding.

Conclusion

In today's blog, we have seen how to add SpringDoc-OpenAPI and Swagger-UI based RESTful API documentations.

Thank you for reading, I hope you found this article useful.

If you enjoyed reading, please consider following me here on Hashnode and also on Twitter / GitHub / LinkedIn .