Spring Boot OpenAPI 3 Example

The open API specification is a widely used standard for API documentation. The Spring boot OpenAPI project is a community project. Also, this is similar to the spring fox project that supports documentation of REST APIs.

In this article, we will learn how to use the Spring boot open API library to document spring boot REST APIs.

We will also learn how to customize the swagger documentation and how to invoke the API from swagger UI and get the response.

Version details:

  • Spring boot version 2.6.3
  • Spring doc OpenAPI libarry : 1.6.6

Table of Contents

Configuring Spring Boot With Open API

Below are the steps to configure the Spring boot application with the Open API documentation library.

  • Adding the springdoc-openapi-ui maven library.
  • Defining an OpenAPI spring configuration bean.
  • Finally, use the open API annotations to document the APIs.

Let’s start with the configuration now.

Adding Maven dependency

Add the springdoc-openapi-ui maven dependency to the application’s pom.xml file.

This dependency also contains the swagger-ui library.

Swagger UI is a standardized API documentation UI interface. We can also use the Swagger UI to interact with the application’s APIs.

<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-ui</artifactId>
    <version>1.6.6</version>
</dependency>

Note: We also need other dependencies like spring-boot-starter-web, Lombok, etc. We have skipped these in the above code snippet.

Adding Spring Boot OpenAPI configuration class

We can now create a configuration class and define the OpenAPI spring bean.

We can also customize the documentation, as shown below.

@Configuration
public class OpenApiConfig {
    @Bean
    public OpenAPI openApi() {
        return new OpenAPI()
                .info(new Info()
                        .title("Title")
                        .description("my little API")
                        .version("v1.0")
                        .contact(new Contact()
                                .name("Arun")
                                .url("https://asbnotebook.com")
                                .email("asbnotebook@gmail.com"))
                        .termsOfService("TOC")
                        .license(new License().name("License").url("#"))
                );
    }
}

The above configuration also shows how to set the API information like API title, description, version, contact information, etc.

Specify the swagger configuration

Add the below application.properties configuration file.

springdoc.swagger-ui.path=/openapi/swagger-ui.html
springdoc.api-docs.path=/openapi/v3/api-docs
springdoc.packagesToScan=com.asbnotebook.example.controller
springdoc.pathsToMatch=/**

Here, we are specifying the below configurations.

  • swagger-ui.path: The swagger UI path value.
  • api-docs.path: Retuns the documentation is JSON format.
  • packagesToScan: Generates openAPI documentation for listed java package.
  • pathsToMatch: To specify the URL pattern to filter out certain URLs. The /** value includes all available APIs in the documentation.
  • With the last two configuration properties, we can also exclude the packages or URLs that are not required to be documented.

Testing the configuration

Run the application, and navigate to the swagger UI URL http://localhost:8080/openapi/swagger-ui.html

We can observe the customized swagger UI documentation as shown below.

openapi configuration

We can also check the api-docs.path by accessing the URL path /openapi/v3/api-docs.

open-api-docs-path

Using the OpenAPI for documenting the APIs

Now the basic configuration is complete.

We can also use the open API annotations to document our APIs.

Creating a DTO class

Let’s create a Student java class as shown below.

We will use this DTO class in the student API response.

Also, this DTO is part of the API response, and swagger UI will add this under the Schemas section of the documentation.

@Getter
@Setter
public class Student {
    
    private String name;
    private Long id;
}

Creating a REST Controller class

Create a Spring boot REST API that returns a list of hardcoded student objects.

Here, we are exposing an HTTP GET API at location /students.

The API returns a list of student objects.

@Tag(description = "Student resources that provides access to availabe student data", 
    name = "Student Resource")
@RestController("/")
public class StudentController {
    @Operation(summary = "Get students", 
            description = "Provides all available students list")
    @ApiResponses(value = { 
            @ApiResponse(responseCode = "200", 
                    description = "${api.response-codes.ok.desc}"),
            @ApiResponse(responseCode = "400", 
                    description = "${api.response-codes.badRequest.desc}", 
                    content = { @Content(examples = { @ExampleObject(value = "") }) }),
            @ApiResponse(responseCode = "404", 
                    description = "${api.response-codes.notFound.desc}", 
                    content = { @Content(examples = { @ExampleObject(value = "") }) }) })
    @GetMapping("/students")
    public List<Student> getStudents() {
        List<Student> students = new ArrayList<>();
        
        Student student = new Student();
        student.setId(1L);
        student.setName("Arun");
        students.add(student);
        return students;
    }
}

We have also used the below open API annotations to document the API.

  • @Tag: This is a class level annotation. We can use this annotation to customize the resource details like resource name, description, etc.
  • @Operation: We can use this annotation to customize the name and description of the API.
  • @ApiResponses: We can use this annotation to specify the API response format such as success and error response formats, etc. In the above configuration, we have configured HTTP response for 400, 200, and 404 HTTP error codes.

In the above configuration, we have externalized the API response descriptions.

Also, these configuration properties are resolved from the application.properties configuration file.

Finally, add the below custom configuration properties to the application.properties file of the spring boot application.

api.response-codes.ok.desc=OK
api.response-codes.badRequest.desc=BAD_REQUEST
api.response-codes.notFound.desc=NOT_FOUND

Testing the API documentation

Finally, we can test our REST API documentation generated by the open API documentation library.

Run the application again.

We can observe our REST API documentation as shown below.

spring boot swagger ui

We can also observe the Schemas part, which contains our Student DTO structure.

swagger schema section

A detailed view of the Student resource is given below.

Also, we can observe the API’s possible response formats and error codes.

swagger-openapi-resource-example

We can also use the swagger UI to test the API.

Click on the Try it out button to invoke the API.

We will get the actual API response as output as shown below.

executing swagger API

We can also observe the response headers and response code on the above image.

Conclusion

In this article, we learned the basics of the Spring boot Open API library.

We also learned how can leverage the spring boot Open API library to generate documentation for REST APIs.

We also learned to customize the documentation information by adding the necessary spring bean configuration.

Finally, we learned how to customize documentation configurations and available annotations.

Example code is available on Github.

Spring Boot OpenAPI 3 Example
Scroll to top

Discover more from ASB Notebook

Subscribe now to keep reading and get access to the full archive.

Continue reading