2020-04-24

Setting up Swagger in Spring REST API

Setting Up Swagger with a Spring REST API

1. Overview Overview

Good documentation is important when creating REST APIs.

Moreover, whenever you change the API, you must specify the same in the reference documentation. It is very tedious to reflect this manually, so automating it is essential.

In this tutorial we will  look at Swagger 2 for a Spring REST web service . In this document, we will use Springfox, the implementation of the Swager 2 specification.

If you are not familiar with Swagger, we recommend that you visit the official webpage before reading this article  .

2.  Target Project

REST service creation is not a category of this document, so users should already have a project that can be easily applied. If not already there, the following link would be a good starting point:

Build a REST API with Spring 4 and Java Config article
Building a RESTful Web Service .

3. Adding the Maven Dependency

As mentioned above, we will use the Spring Fox implementation of the Swager specification. Add the following dependency to the Maven project's pom.xml file.

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

4.  Integrating Swagger 2 into the Project

Java settings Java Configuration
Swagger's configuration is mainly   centered on the Docket bean configuration:

@Configuration
@EnableSwagger2
public class SwaggerConfig {                                   
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2) 
          .select()                                 
          .apis(RequestHandlerSelectors.any())             
          .paths(PathSelectors.any())                         
          .build();                                         
    }
}
Swager  2 is  enabled with the @ EnableSwagger2 annotation setting.

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

The description for selection of  RequestHandler s  can be set  with the help of RequestHandlerSelectors and  PathSelectors  . If you use both  any ()  , your entire API will be documented through Swagger.

This setup allows you to integrate Swagger 2 into your existing Spring Boot project. Other Spring projects require some extra work.

Setting up without a spring boot Configuration Without Spring Boot
If you don't use Spring Boot, users won't benefit from autoconfiguration of resource handlers. The Swagger UI adds a set of resources, which the  user  must configure as a part  and a class that extends  WebMvcConfigurerAdapter with the @EnableWebMvc  annotation .

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("swagger-ui.html")
      .addResourceLocations("classpath:/META-INF/resources/");

    registry.addResourceHandler("/webjars/**")
      .addResourceLocations("classpath:/META-INF/resources/webjars/");
}


Verification  Verification
To verify that Spring Fox works, try the following URL using a browser:

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

You can see a lot of JSON responses with key-value pairs with very low readability. Fortunately, Swagger provides a Swagger UI for this.

5. Swagger UI


The Swagger UI is a built-in solution that makes it easier for the user to create API documents generated by Swagger.
Seuwegeo spring Fox to use UI  Enabling Springfox's UI SWAGGER
To use the Swager UI, you need one additional Maven dependency:

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.2.2</version>
</dependency>
Now the user can test it by accessing the following link in the browser-  http: // localhost: 8080 / your-app-root / swagger-ui.html

The following page will be displayed:

Seuwegeo article Tour  Exploring Swagger Documentation
Now you will see a list of all controllers defined in your application. Clicking on one of them will list the valid HTTP methods  ( DELETE ,  GET ,  HEAD ,  OPTIONS ,  PATCH , POST ,  PUT ) .

Extending each method provides additional useful data, such as response status , response status , content-type, and parameter list. You can also test each method through the UI.

The ability of Swager to be synchronized with the user's code is very important. To demonstrate this, let's add a new controller to the application:

@RestController
public class CustomController {

    @RequestMapping(value = "/custom", method = RequestMethod.POST)
    public String custom() {
        return "custom";
    }
}
Now if you refresh the Swagger documentation, you  should see custom-controller in the controller list  . As you created above, only one POST method will be shown.

6. Advanced Configuration


In the Docket  bean of the user application,  more configuration is possible for the user to generate the API document.

The response code seuwegeo filtering API  Filtering API for SWAGGER's Response,

Documenting the entire user API is usually not desirable. The user can limit Swager's response code by  putting parameters in apis ()  and paths () of the  Docket  class  .

As seen above,  RequestHandlerSelectors  allow  any  or  none  description, but   you can also filter the API based on base package, class annotation, and method annotations.

PathSelectors provide additional filtering through statements that scan the request paths  of the user application . Any () ,  none (),  regex () , or ant ()  can be used.

In the example below, we use the ant ()  predicate to make  Swagger  include only certain packages and controllers in a specific path.

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

Custom info  Custom Information
Seuwegeo also a response code to the user information, such as the "Api Documentation", "Created by  Contact Email", "Apache 2.0" that can be customized  helps provide some default.

To modify these values, you can use the  apiInfo (ApiInfo apiInfo)  method. The ApiInfo  class 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() {
    ApiInfo apiInfo = new ApiInfo(
      "My REST API",
      "Some custom description of API.",
      "API TOS",
      "Terms of service",
      "myeaddress@company.com",
      "License of API",
      "API license URL");
    return apiInfo;
}

Custom method response messages  Custom Methods Response Messages
Swagger allows  globally overriding response messages of HTTP methods  through HTTP method through Docket 's  globalResponseMessage ()  method  . First, we need to configure Swagger not to use the default response message.

 To override the 500  and 403response messages  for all GET methods,  you need to add some code to theDocket initialization block. (Initialization code was excluded here):


.useDefaultResponseMessages(false)                                 
.globalResponseMessage(RequestMethod.GET,                   
  newArrayList(new ResponseMessageBuilder() 
    .code(500)
    .message("500 message")
    .responseModel(new ModelRef("Error"))
    .build(),
    new ResponseMessageBuilder()
      .code(403)
      .message("Forbidden!")
      .build()));

7. Conclusion Conclusion

In this tutorial we set up Swagger 2, which generates documentation for the Spring REST API. We also looked at ways to visualize and customize Swagger's output.

The full implementation of this tutorial can be found in the following github project -it's Eclipse-based and can be easily imported and returned.

No comments:

Post a Comment