y0ngb1n

Aben Blog

欢迎来到我的技术小黑屋ヾ(◍°∇°◍)ノ゙
github

Using Swagger Documentation in a Spring Boot Project

The project is hosted on GitHub: y0ngb1n/spring-boot-samples. Feel free to Star, Fork 😘


Swagger, also known as "Silk Stocking Brother," claims to allow programmers to generate interface documentation while coding.

Adding Swagger 2 Dependency#

Add the required Swagger 2 dependency in pom.xml:

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

Adding Swagger Java Configuration#

@Configuration
@EnableSwagger2
public class SwaggerConfig {

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

Swagger Annotation Explanation#

Swagger uses annotations to indicate that an interface will generate documentation, including interface name, request method, parameters, return information, and more.

  • @Api: Describes the entire class and its role as a controller.
  • @ApiOperation: Describes a method or interface within a class.
  • @ApiParam: Describes a single parameter.
  • @ApiModel: Uses an object to receive parameters.
  • @ApiProperty: Describes a field of an object when receiving parameters.
  • @ApiResponse: Describes one of the HTTP responses.
  • @ApiResponses: Describes the overall HTTP responses.
  • @ApiIgnore: Ignores the API using this annotation.
  • @ApiImplicitParam: Describes a request parameter.
  • @ApiImplicitParams: Describes multiple request parameters.

These are the most commonly used annotations.

For more information on other annotations, please refer to: https://github.com/swagger-api/swagger-core/wiki/Annotations

For more information, please refer to the Swagger Annotation Documentation

Adding Controller and Model to Test the Effect#

@Api(value = "User Management", description = "Operations for managing user information")
@RestController
@RequestMapping(path = "/sample/users")
public class UserController {

  private static Map<Long, UserModel> users = Collections.synchronizedMap(new HashMap<>());

  @ApiOperation(value = "User List")
  @GetMapping(path = "/")
  public List<UserModel> getUserList() {
    return new ArrayList<>(users.values());
  }

  @ApiOperation(value = "Create User", notes = "Creates a user based on the User object")
  @ApiImplicitParam(name = "user", value = "User details", required = true, dataTypeClass = UserModel.class)
  @PostMapping(path = "/")
  public UserModel createUser(@RequestBody UserModel user) {
    users.put(user.getId(), user);
    return user;
  }

  @ApiOperation(value = "User Details", notes = "Gets detailed user information based on ID")
  @ApiImplicitParam(name = "id", value = "User ID", required = true, dataType = "Long")
  @GetMapping(path = "/{id}")
  public UserModel getUser(@PathVariable Long id) {
    return users.get(id);
  }

  @ApiOperation(value = "Update User Details", notes = "Updates user details based on ID and User information")
  @ApiImplicitParams({
      @ApiImplicitParam(name = "id", value = "User ID", required = true, dataTypeClass = Long.class),
      @ApiImplicitParam(name = "user", value = "User details", required = true, dataTypeClass = UserModel.class)
  })
  @PutMapping(path = "/{id}")
  public UserModel updateUser(@PathVariable Long id, @RequestBody UserModel user) {
    UserModel updateUser = users.get(id);
    updateUser.setName(user.getName());
    updateUser.setAge(user.getAge());
    updateUser.setEmail(user.getEmail());
    users.put(id, updateUser);
    return updateUser;
  }

  @ApiOperation(value = "Delete User", notes = "Deletes a user based on ID")
  @ApiImplicitParam(name = "id", value = "User ID", required = true, dataType = "Long")
  @DeleteMapping(path = "/{id}")
  public String deleteUser(@PathVariable Long id) {
    users.remove(id);
    return "success";
  }
}
@Data
@ApiModel(value = "User Model", description = "Entity class for user details")
public class UserModel {

  @ApiModelProperty(value = "User ID")
  private Long id;

  @ApiModelProperty(value = "Name", allowableValues = "y0ngb1n, tony")
  private String name;

  @ApiModelProperty(value = "Age", allowableValues = "range[1, 120]")
  private Integer age;

  @ApiModelProperty(value = "Email")
  private String email;
}

You can now start the project to verify if Swagger 2 integration was successful. After starting the project, you can see in the logs that Swagger has added the access endpoint /v2/api-docs:

...
2019-12-28 22:19:53.880  INFO 11935 --- [main] pertySourcedRequestMappingHandlerMapping : Mapped URL path [/v2/api-docs] onto method [public org.springframework.http.ResponseEntity<springfox.documentation.spring.web.json.Json> springfox.documentation.swagger2.web.Swagger2Controller.getDocumentation(java.lang.String,javax.servlet.http.HttpServletRequest)]
...

By accessing http://localhost:8080/v2/api-docs in a browser, you will find that the returned result is a JSON string with poor readability. Fortunately, Swagger 2 provides us with a visual interactive interface called SwaggerUI. Let's try it out.

Adding Swagger UI Dependency#

Similar to the previous step, add the required Swagger UI dependency in pom.xml:

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

After adding the dependency, restart the project and access http://localhost:8080/swagger-ui.html in a browser to see the following effect:

Swagger 2

At this point, the Swagger integration is successful. For more advanced operations, continue reading the documentation or explore further using the reference links below. Happy learning!

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.