API Documentation with Swagger/OpenAPI


Table of Contents

  1. Introduction to API Documentation
  2. What is Swagger and OpenAPI?
  3. Setting Up Swagger in Spring Boot
  4. Annotating Your API with Swagger Annotations
  5. Configuring Swagger UI
  6. Customizing Swagger Documentation
  7. Using Swagger with Spring Security
  8. Conclusion

1. Introduction to API Documentation

API documentation is an essential part of developing RESTful APIs. It provides a detailed description of the available endpoints, their parameters, request/response formats, and status codes, allowing other developers and consumers to interact with the API correctly.

While API documentation can be created manually, tools like Swagger and OpenAPI provide automatic documentation generation, ensuring consistency and saving time. These tools make your API more accessible, clear, and interactive for other developers and API consumers.


2. What is Swagger and OpenAPI?

  • Swagger is a suite of tools for API development that includes a specification for describing REST APIs and tools for generating interactive documentation. Swagger is now part of the OpenAPI Specification (OAS), which is a standardized format for describing RESTful APIs. The OAS specification defines a set of rules and standards for describing APIs in a machine-readable format (usually JSON or YAML).
  • OpenAPI (formerly known as Swagger) is a specification for defining APIs. It provides a standard, language-agnostic interface for describing REST APIs. Tools like Swagger UI, Swagger Codegen, and Swagger Editor allow developers to work with OpenAPI specifications and interact with APIs.

3. Setting Up Swagger in Spring Boot

To integrate Swagger with a Spring Boot application, you need to include the required dependencies.

Step 1: Add Swagger Dependencies

If you’re using Maven, add the following dependencies in your pom.xml:

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

For Gradle:

gradleCopyEditimplementation 'io.springfox:springfox-boot-starter:3.0.0'

Step 2: Enable Swagger in Spring Boot

Create a configuration class to enable Swagger:

javaCopyEdit@Configuration
@EnableSwagger2
public class SwaggerConfig {
}

For Spring Boot 2.x and later, you may need to use springfox-boot-starter instead of @EnableSwagger2, as it is automatically enabled via the starter.


4. Annotating Your API with Swagger Annotations

Swagger uses annotations to generate API documentation for each of your endpoints. Below are the key annotations to use:

@Api: Describes the entire controller class.

javaCopyEdit@Api(value = "Employee Management System", tags = {"Employee"})
@RestController
@RequestMapping("/api/employees")
public class EmployeeController {
}

@ApiOperation: Describes an individual API operation.

javaCopyEdit@ApiOperation(value = "Get an employee by ID", response = EmployeeDTO.class)
@GetMapping("/{id}")
public ResponseEntity<EmployeeDTO> getEmployeeById(@PathVariable Long id) {
    EmployeeDTO employeeDTO = employeeService.getEmployeeDTO(id);
    return ResponseEntity.ok(employeeDTO);
}

@ApiParam: Describes a parameter in an API operation.

javaCopyEdit@ApiOperation(value = "Update an employee's details")
@PutMapping("/{id}")
public ResponseEntity<EmployeeDTO> updateEmployee(
    @ApiParam(value = "Employee ID", required = true) @PathVariable Long id,
    @RequestBody EmployeeDTO employeeDTO
) {
    employeeService.updateEmployee(id, employeeDTO);
    return ResponseEntity.ok(employeeDTO);
}

@ApiResponse: Describes a possible response for an API operation.

javaCopyEdit@ApiOperation(value = "Get all employees")
@ApiResponse(code = 200, message = "Successfully retrieved the list of employees")
@GetMapping("/")
public List<EmployeeDTO> getAllEmployees() {
    return employeeService.getAllEmployees();
}

5. Configuring Swagger UI

Swagger UI is a web-based interface for interacting with your API documentation. To enable Swagger UI in your Spring Boot application, ensure that the following configuration is set:

Step 1: Accessing Swagger UI

By default, Swagger UI is accessible at the following URL:

bashCopyEdithttp://localhost:8080/swagger-ui/

Step 2: Customize Swagger UI

You can customize the look and feel of Swagger UI by modifying its configuration. For example:

javaCopyEdit@Configuration
public class SwaggerConfig {

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.api"))
                .paths(PathSelectors.any())
                .build()
                .apiInfo(apiInfo());
    }

    private ApiInfo apiInfo() {
        return new ApiInfo(
                "Employee API",
                "API for managing employees in the system",
                "1.0",
                "Terms of service URL",
                new Contact("John Doe", "www.example.com", "[email protected]"),
                "License of API",
                "API License URL",
                Collections.emptyList());
    }
}

6. Customizing Swagger Documentation

Swagger allows you to customize the documentation to suit your needs. You can specify custom descriptions, API versioning, and additional metadata.

Customizing Model Descriptions

You can customize descriptions for your models using annotations like @ApiModel and @ApiModelProperty:

javaCopyEdit@ApiModel(description = "Employee details")
public class EmployeeDTO {

    @ApiModelProperty(notes = "Unique identifier of the employee")
    private Long id;

    @ApiModelProperty(notes = "Name of the employee")
    private String name;

    @ApiModelProperty(notes = "Department of the employee")
    private String department;

    // Getters and setters
}

API Versioning

You can use Swagger’s @ApiVersion annotation to document different versions of your API.

javaCopyEdit@ApiVersion(1)
@GetMapping("/v1/employees")
public List<EmployeeDTO> getEmployeesV1() {
    return employeeService.getAllEmployeesV1();
}

@ApiVersion(2)
@GetMapping("/v2/employees")
public List<EmployeeDTO> getEmployeesV2() {
    return employeeService.getAllEmployeesV2();
}

7. Using Swagger with Spring Security

When your API is secured with Spring Security, Swagger documentation may be blocked by the security filters. You can configure Spring Security to allow access to Swagger UI and API documentation by permitting specific endpoints:

javaCopyEdit@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
            .antMatchers("/swagger-ui/**", "/v2/api-docs").permitAll()
            .anyRequest().authenticated()
            .and()
            .httpBasic();
    }
}

This configuration allows unrestricted access to Swagger UI and API documentation while securing the other endpoints.


8. Conclusion

Using Swagger/OpenAPI for API documentation provides several advantages for developers and consumers, including easy-to-navigate interactive documentation and the ability to auto-generate API documentation. With Swagger integrated into your Spring Boot application, you can enhance the developer experience and improve the clarity of your API.

Key Takeaways:

  • Swagger/OpenAPI offers a powerful, standardized way to describe REST APIs.
  • Integrating Swagger into Spring Boot allows automatic documentation generation and customization.
  • The Swagger UI provides an interactive interface for API testing and visualization.
  • Spring Security can be configured to allow access to Swagger even in secured applications.

By following this guide, you’ll be able to set up and customize Swagger in your Spring Boot applications, providing rich, accurate API documentation for easier integration and development.