DEV Community

Anshul Bansal
Anshul Bansal

Posted on • Updated on

Swagger-2 API documentation for Spring App using Springfox

1. Overview

Spring is a very popular JEE framework to create web applications.

Often, we use Spring technologies to expose APIs to third-party integrations. At that time, our APIs require a detailed specification that helps in easy integrations.

In this tutorial, we'll explore the Springfox Java libraries to generate Swagger based API specifications for the Spring application.

2. Springfox

Springfox is a set of Java libraries, that has evolved from the swagger-springmvc project.

It automates the generation of specifications for JSON APIs, implemented with the Spring framework. Also, it provides libraries to integrate the Swagger UI to interact with APIs.

Springfox examines the Spring application at runtime and generates the API specifications based on configurations and annotations.

Let's explore Swagger 2 integration with Spring REST API. Also, we'll touch upon the basic configurations.

3. Setup

Let's add the latest springfox-swagger2 Maven dependency to our Spring Boot application:

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>
Enter fullscreen mode Exit fullscreen mode

Similarly, we can add the springfox-swagger2 dependency to a Gradle based Spring project:

compile "io.springfox:springfox-swagger2:2.9.2"
Enter fullscreen mode Exit fullscreen mode

4. @EnableSwagger2

Now that we've set up the Springfox dependency. Let's enable Swagger 2 to generate the API specifications.

To do so, we'll add the @EnableSwagger2 annotation to the main class of our application:

@EnableSwagger2
@SpringBootApplication
public class SpringfoxApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringfoxApplication.class, args);
    }
}
Enter fullscreen mode Exit fullscreen mode

Let's start the application with the Maven command:

mvn spring-boot:run
Enter fullscreen mode Exit fullscreen mode

Voila! The API specifications are ready.

As a result, we can access the specifications in the JSON format at localhost:8080/v2/api-docs:

Alt Text

5. Swagger UI

The API specification in the JSON format is not readable and difficult to follow. As a result, we need UI support that makes interaction with the API specifications easy.

Therefore, let's integrate the Swagger UI to our application, by adding the springfox-swagger-ui dependency into the pom.xml:

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>
Enter fullscreen mode Exit fullscreen mode

Then, we'll restart the app and access the Swagger UI at localhost:8080/swagger-ui.html:

Alt Text

6. Spring REST API

Let's explore the Swagger 2 integration with the Spring REST API.

First, let's create an entity named User:

@Entity
public class User{
    @Id
    private Long id;
    private String firstName;
    private int age;
    private String email;

    //getters and setters
}
Enter fullscreen mode Exit fullscreen mode

Then, we'll create the UserRepository to add CRUD operations on the User entity:

@Repository
public interface UserRepository extends CrudRepository<User, Long> {
}
Enter fullscreen mode Exit fullscreen mode

Now, we'll create the UserController for the REST APIs:

@Controller
@RequestMapping(value = "/api/user", produces = MediaType.APPLICATION_JSON_VALUE)
public class UserController {
    @Autowired
    private UserRepository userRepository;

    @PostMapping
    public @ResponseBody ResponseEntity<User> createUser(@RequestBody User user) {
        userRepository.save(user);
        return new ResponseEntity<>(user, HttpStatus.OK);
    }

    @GetMapping
    public @ResponseBody ResponseEntity<User> getUser(@RequestParam Long id) {
        Optional<User> user = userRepository.findById(id);
        return new ResponseEntity<>(user.get(), HttpStatus.OK);
    }
}
Enter fullscreen mode Exit fullscreen mode

Now we've got the entity, repository, and controller in place. Let's integrate everything into the main class:

@SpringBootApplication
@EnableSwagger2
public class SpringfoxApplication {
    // ...
}
Enter fullscreen mode Exit fullscreen mode

Then, we'll restart the application to see the changes:

Alt Text

Here, we can see the specifications are generated for the UserController APIs.

7. Configuration

Let's explore the basics of Springfox configuration.

We can configure the API specifications using the Docket class. For this, we should create a method in the main class registered as a bean and return a Docket instance.

Let's create a springfoxAppInfo bean method in the SpringfoxApplication:

public class SpringfoxApplication {
    //...

    @Bean
    public Docket springfoxAppInfo() {
        return new Docket(DocumentationType.SWAGGER_2)
          .groupName("Springfox-api")
          .select()
          .paths(paths())
          .build();
          .apiInfo(apiInfo());
    }

    private Predicate<String> paths() {
        return regex("/api/.*");       
    }

    private ApiInfo apiInfo() {
        return new ApiInfo(
          "Springfox API specification", 
          "Spring REST APIs", 
          "", 
          "", 
          null, 
          "License of API",
          "API license URL", 
          Collections.emptyList());
    }
}
Enter fullscreen mode Exit fullscreen mode

Here, we've changed a few properties like the groupName and apiInfo. Also, we've restricted our API specifications to the /api URI paths.

Let's restart the application and check out the differences in the specifications:

Alt Text

Here, we can observe that the API info has changed. Also, the specification is available only for UserController based on the /api URI path mentioned.

8. Conclusion

In this article, we've explored the Springfox suite of libraries for generating specifications of the APIs, implemented using the Spring framework.

To begin with, we've created a Spring Boot application and integrate Swagger 2 APIs to create the specifications. Also, we've seen integration with the Swagger UI.

Then, we've examined ways to integrate Swagger into Spring REST APIs.

Last, we've touched upon the basics of Swagger UI configuration.

Please find the entire code implementations over on Github.

Would love to hear your thoughts on the article. Have any questions? Any feedback? Please comment!!!

Top comments (0)