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:

Adding Swagger Java Configuration#

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#

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:

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:

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.