Setting Up Swagger 2 with Spring REST API

Reading Time: 4 minutes

Introduction

In this article, we’ll dive into the Swagger framework . We’ll use Swagger2 to design, build, and document a Spring Boot RESTful API and Swagger UI to observe our endpoints and test them.

Nowadays, front-end and back-end components often separate a web application. Usually, we expose APIs as a back-end component for the front-end component or third-party app integrations.

In such a scenario, it is essential to have proper specifications for the back-end APIs. At the same time, the API documentation should be informative, readable, and easy to follow.

Moreover, reference documentation should simultaneously describe every change in the API. Accomplishing this manually is a tedious exercise, so automation of the process was inevitable.

Adding the Maven Dependency

As mentioned above, we will use the Springfox implementation of the Swagger specification. The latest version can be found on Maven Central.

To add it to our Maven project, we need a dependency in the pom.xml file:

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>3.0.0</version>
</dependency>

Integrating Swagger 2 Into the Project

Java Configuration

The configuration of Swagger mainly centers around the Docket bean:

@Configuration
public class SpringFoxConfig {                                    
    @Bean
    public Docket api() { 
        return new Docket(DocumentationType.SWAGGER_2)  
          .select()                                  
          .apis(RequestHandlerSelectors.any())              
          .paths(PathSelectors.any())                          
          .build();                                           
    }
}

After defining the Docket bean, its select() method returns an instance of ApiSelectorBuilder, which provides a way to control the endpoints exposed by Swagger.

We can configure predicates for selecting RequestHandlers with the help of RequestHandlerSelectors and PathSelectors. Using any() for both will make documentation for our entire API available through Swagger.

Verification

To verify that Springfox is working, we can visit this URL in our browser:

http://localhost:8080/your-app-root/api/v2/api-docs

The result is a JSON response with a large number of key-value pairs, which is not very human readable. Fortunately, Swagger provides Swagger UI for this purpose.

Swagger UI

Swagger UI is a built-in solution that makes user interaction with the Swagger-generated API documentation much easier.

Enabling Springfox’s Swagger UI

To use Swagger UI, we need to add an additional Maven dependency:

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

Now we can test it in our browser by visiting:

http://localhost:8080/your-app-root/swagger-ui/

Exploring Swagger Documentation

Within Swagger’s response is a list of all controllers defined in our application. Clicking on any of them will list the valid HTTP methods (DELETEGETHEADOPTIONSPATCHPOSTPUT).

Expanding each method provides additional useful data, such as response status, content-type, and a list of parameters. It is also possible to try each method using the UI.

Swagger’s ability to be synchronized with our code base is crucial. To demonstrate this, we can add a new controller to our application:

@RestController
public class CustomController {

    @RequestMapping(value = "/custom", method = RequestMethod.POST)
    public String custom() {
        return "custom";
    }
}

Now if we refresh the Swagger documentation, we see custom-controller in the list of controllers. As we know, there is only one method (POST) shown in Swagger’s response.

Spring Data REST

Now 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
}

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

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

Last, we’ll import the SpringDataRestConfiguration class to the SpringFoxConfig class:

@EnableSwagger2WebMvc
@Import(SpringDataRestConfiguration.class)
public class SpringFoxConfig {
    //...
}

Note: We’ve used the @EnableSwagger2WebMvc annotation to enable Swagger, as it has replaced the @EnableSwagger2 annotation in version 3 of the libraries.

Let’s restart the application to generate the specifications for the Spring Data REST APIs:

We can see that Springfox has generated the specifications for the User entity with HTTP methods like GETPOST, PUT, PATCH, and DELETE.

Advanced Configuration

The Docket bean of our application can be configured to give us more control over the API documentation generation process.

Filtering API for Swagger’s Response

It is not always desirable to expose the documentation for the entire API , So we can restrict Swagger’s response by passing parameters to the apis() and paths() methods of the Docket class.

As seen above, RequestHandlerSelectors allows using the any or none predicates but can also be used to filter the API according to the base package, class annotation, and method annotations.

PathSelectors provides additional filtering with predicates, which scan the request paths of our application. We can use any()none(), regex(), or ant().

In the example below, we will instruct Swagger to include only controllers from a particular package, with specific paths, using the ant() predicate:

@Bean
public Docket api() {                
    return new Docket(DocumentationType.SWAGGER_2)          
      .select()                                       
      .apis(RequestHandlerSelectors.basePackage("com.example.web.controller"))
      .paths(PathSelectors.ant("/foos/*"))                     
      .build();
}

Custom Information

Swagger also provides some default values in its response, which we can customize, such as “Api Documentation”, “Created by Contact Email”, and “Apache 2.0”.

To change these values, we can use the apiInfo(ApiInfo apiInfo) method — the ApiInfo class that contains custom information about the API:

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

private ApiInfo apiInfo() {
    return new ApiInfo(
      "My REST API", 
      "Some custom description of API.", 
      "API TOS", 
      "Terms of service", 
      new Contact("John Doe", "www.example.com", "myeaddress@company.com"), 
      "License of API", "API license URL", Collections.emptyList());
}

Conclusion

In this article, we set up Swagger 2 to generate documentation for a Spring REST API. We also explored ways to visualize and customize Swagger’s output.

Reference Link :- https://en.wikipedia.org/wiki/Swagger_(software).

Written by 

KRISHNA JAISWAL is Software Consultant Trainee at Knoldus. He is passionate about JAVA , MYSQL , having knowledge of C , C++ and much more. He is recognised as a good team player, a dedicated and responsible professional, and a technology enthusiast. He is a quick learner & curious to learn new technologies. His hobbies include reading Books , listening Music and playing Cricket .

Discover more from Knoldus Blogs

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

Continue reading