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:
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!
🔗️ Reference Links#
- https://www.baeldung.com/swagger-2-documentation-for-spring-rest-api
- https://www.tutorialspoint.com/spring_boot/spring_boot_enabling_swagger2.htm
- http://blog.didispace.com/tags/Swagger/
- https://www.ibm.com/developerworks/cn/java/j-using-swagger-in-a-spring-boot-project/index.html
- https://mp.weixin.qq.com/s/EYnL7T0yOgNXYIrBWBg8hg
- https://github.com/dyc87112/swagger-butler
- https://github.com/SpringForAll/spring-boot-starter-swagger
- https://blog.csdn.net/lilyssh/article/details/82944507