Swagger-2 API documentation for Spring App using Springfox
Tags: java, tutorial, spring, swagger2
Published: 2019-12-16 21:58:00

##1. Overview

[Spring](https://spring.io/) 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](https://swagger.io/) based API specifications for the Spring application.

##2. Springfox

Springfox is a set of Java libraries, that has evolved from the [*swagger-springmvc*](https://search.maven.org/search?q=g:com.mangofactory%20a: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](https://swagger.io/docs/specification/2-0/basic-structure/) integration with Spring REST API. Also, we'll touch upon the basic configurations.

##3. Setup

Let's add the latest [*springfox-swagger2*](https://search.maven.org/search?q=g:io.springfox%20a:springfox-swagger2) Maven dependency to our Spring Boot application:

```xml    
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>
```

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

```groovy
compile "io.springfox:springfox-swagger2:2.9.2"
```

##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*](http://springfox.github.io/springfox/javadoc/current/index.html?springfox/documentation/swagger2/annotations/EnableSwagger2.html) annotation to the main class of our application:

```java    
@EnableSwagger2
@SpringBootApplication
public class SpringfoxApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringfoxApplication.class, args);
    }
}
```

Let's start the application with the Maven command:

```shell
mvn spring-boot:run
```

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](https://thepracticaldev.s3.amazonaws.com/i/27ijiht4vd8iw65swvok.png)

##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](https://swagger.io/tools/swagger-ui/) to our application, by adding the [*springfox-swagger-ui*](https://search.maven.org/search?q=g:io.springfox%20a:springfox-swagger-ui) dependency into the *pom.xml*:

```xml    
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>
```

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

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/r1q9sd6u3rv7xxucer7i.png)

##6. Spring REST API

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

First, let's create an entity named *User*:

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

    //getters and setters
}
```

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

```java
@Repository
public interface UserRepository extends CrudRepository<User, Long> {
}
```

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

```java
@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);
    }
}
```

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

```java
@SpringBootApplication
@EnableSwagger2
public class SpringfoxApplication {
    // ...
}
```

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

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/h7gu1ur7ft08pzzqj42x.png)

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*](http://springfox.github.io/springfox/javadoc/current/springfox/documentation/spring/web/plugins/Docket.html) 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*:

```java
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());
    }
}
```

Here, we've changed a few properties like the *groupName* and [*apiInfo*](http://springfox.github.io/springfox/javadoc/current/springfox/documentation/service/ApiInfo.html). 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](https://thepracticaldev.s3.amazonaws.com/i/rvkhtjgbkghdtekig4ua.png)

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](https://github.com/SmartyAnsh/springfox).

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