In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article focuses on "how to integrate Swagger2 development API documents", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to integrate Swagger2 to develop API documents.
Preface
It is believed that many back-end developers will encounter the need to write api documents in the project, whether it is to provide better docking for front-end, mobile, etc., or to facilitate future handover, they will be required to write api documents.
There are many pain points in handwritten api documents:
When the document is updated, it needs to be sent to the docker again.
The interface is so right that handwritten documents are difficult to manage.
The result returned by the API is not clear
Can not directly test the interface online, usually need to use tools, such as postman, etc.
Swagger solves this problem very well.
Introduction to Swagger
Swagger is a specification and complete framework for generating, describing, invoking, and visualizing RESTful-style Web services. The overall goal is to have the client and the file system update at the same speed as the server. The file's methods, parameters, and models are tightly integrated into the server-side code, allowing API to always keep synchronized.
Official website: https://swagger.io
Swagger uses 1. Dependent io.springfox springfox-swagger2 2.9.2 io.springfox springfox-swagger-ui 2.9.2 The 2.Swagger configuration class @ Configuration@EnableSwagger2public class SwaggerConfig {@ Bean public Docket buildDocket () {return new Docket (DocumentationType.SWAGGER_2) .apiInfo (buildApiInf ()) / sets the meta-information of api to be included in the json resourcelisting response / / .host ("127.0.0.1 Bean public Docket buildDocket 8080") / / sets the ip and port Or the domain name .select () / starts the generator for api selection / / .apis (RequestHandlerSelectors.any ()) .apis (RequestHandlerSelectors.basePackage ("cn.zwqh.springboot.controller")) / / specifies the controller path .select (PathSelectors.any ()) .build () } private ApiInfo buildApiInf () {Contact contact=new Contact ("light cold in morning fog", "https://www.zwqh.top/","zwqh@clover1314.com");" Return new ApiInfoBuilder () .title ("Swagger Demo Restful API Docs") / / document title .description ("Swagger sample Restful Api document") / / document description .contact (contact) / / contact .version / / version number / / .license (") / / Update the license information for this API / / .license ("). ) / / Update the license for this API Url / / .termsOfServiceUrl (") / / update the terms of service URL .build () }} 3.Spring MVC related configuration @ Configurationpublic class WebMvcConfig extends WebMvcConfigurationSupport {/ * static resource configuration (default) * / @ Override public void addResourceHandlers (ResourceHandlerRegistry registry) {registry.addResourceHandler ("/ * *") .addResourceLocations ("classpath:/static/") / / static resource path registry.addResourceHandler ("swagger-ui.html") .addResourceLocations ("classpath:/META-INF/resources/"); registry.addResourceHandler ("/ webjars/**") .addResourceLocations ("classpath:/META-INF/resources/webjars/"); super.addResourceHandlers (registry);}}
If you do not add this static resource configuration, an error will be reported and the relevant path cannot be found.
4.Model uses Swagger annotations @ ApiModel (value = "UserEntity", description = "user object") public class UserEntity implements Serializable {/ * / private static final long serialVersionUID = 5237730257103305078L; @ ApiModelProperty (value = "user id", name= "id", dataType= "Long", required = false,example = "1", hidden = false) private Long id @ ApiModelProperty (value = "user name", name= "userName", dataType= "String", required = false,example = "Guan Yu") private String userName; @ ApiModelProperty (value = "user gender", name= "userSex", dataType= "String", required = false,example = "male") private String userSex; public Long getId () {return id } public void setId (Long id) {this.id = id;} public String getUserName () {return userName;} public void setUserName (String userName) {this.userName = userName;} public String getUserSex () {return userSex } public void setUserSex (String userSex) {this.userSex = userSex;}} 5. Use the Swagger annotation @ RestController@RequestMapping ("/ api") @ Api (tags = {"Interface grouping 1", "Interface grouping 2"}) public class ApiController {@ Autowired private UserDao userDao in Controller @ GetMapping ("/ getAllUser") @ ApiOperation (value = "get all users", notes = "", httpMethod = "GET", tags = "Interface Group 3") public List getAll () {return userDao.getAll () } @ GetMapping ("/ getUserById") @ ApiOperation (value = "get users according to id", notes = "id required", httpMethod = "GET") @ ApiImplicitParam (name = "id", value = "user id", example = "1", required = true, dataType = "long", paramType = "query") public UserEntity getOne (Long id) {return userDao.getOne (id) } @ PostMapping ("/ getUserByNameAndSex") @ ApiOperation (value = "getting users based on name and sex", notes = "", httpMethod = "POST") @ ApiImplicitParams ({@ ApiImplicitParam (name = "userName", value = "user name", example = "Guan Yu", required = true, dataType = "string", paramType = "query"), @ ApiImplicitParam (name = "userSex") Value = "user gender", example = "male", required = true, dataType = "string", paramType = "query")}) public UserEntity getUserByNameAndSex (String userName, String userSex) {return userDao.getUserByNameAndSex (userName, userSex) } @ PostMapping ("/ insertUser") @ ApiOperation (value = "New user", notes = "pass json" Body ", httpMethod =" POST ") @ ApiImplicitParams ({@ ApiImplicitParam (name =" body ", value =" user object json ", example =" {userName:' foggy', userSex:' male'} ", required = true)}) public String insertUser (@ RequestBody String body) {System.out.println (body) UserEntity user = JSON.parseObject (body, UserEntity.class); userDao.insertUser (user); return "{code:0,msg:'success'}" } @ PostMapping ("/ updateUser") @ ApiOperation (value = "modify user", notes = "pass json Body ", httpMethod =" POST ") @ ApiImplicitParams ({@ ApiImplicitParam (name =" body ", value =" user object json ", example =" {id:23,userName:' misty', userSex:' female'} ", required = true)}) public String updateUser (@ RequestBody String body) {System.out.println (body) UserEntity user = JSON.parseObject (body, UserEntity.class); userDao.updateUser (user); return "{code:0,msg:'success'}" } @ PostMapping ("/ deleteUser") @ ApiOperation (value = "delete user", notes = "id required", httpMethod = "POST") public String deleteUser (@ ApiParam (name = "id", value = "user id", required = true) Long id) {userDao.deleteUser (id); return "{code:0,msg:'success'}";}} 5. test
Visit http://127.0.0.1:8080/swagger-ui.html for interface online testing
Common annotations for Swagger 1.@Api
Used for a class to identify that the class is a resource for swagger. The attributes are as follows:
Tags indicates that if tags has multiple values, it will generate multiple lists.
Value indicates that you can use tags instead of
2.@ApiOperation
Used for a method that represents the operation of a http request. The attributes are as follows:
Value is used for method description
Notes is used to prompt content
A list of tags used by tags for API document control, as appropriate, and can be grouped separately
3.@ApiParam
Used for methods, parameters, field descriptions; represents the addition of metadata to parameters.
Name parameter name
Value parameter description
Is required required
4.@ApiModel
For a class, indicating that the class is described, and that parameters are accepted by the entity class.
Value object name
Description description
5.@ApiModelProperty
Used for methods, fields, that represent a description of the model property or a data operation change.
Value field description
Name overrides attribute names
DataType overrides attribute data types
Is required required
Example gives an example
Hidden hiding
6.@ApiIgnore
Used for class, method, method parameters, indicating that the method or class is ignored and not displayed on the swagger-ui.html.
7.@ApiImplicitParam
Used for methods that represent individual request parameters.
Name parameter name
Value parameter description
DataType data type
ParamType parameter type
Example gives an example
8.@ApiImplicitParams
For methods, contains multiple @ ApiImplicitParam.
9.@ApiResponses @ ApiResponse
Used for a class or method to describe a possible response to an operation.
HTTP status code of the code response
Message response comes with a readable message
10.@ResponseHeader
For methods, response header settings.
Name response header name
Description header description
Response default response class void
ResponseContainer reference configuration in ApiOperation
Swagger exports offline api documents 1. Export documents in AsciiDocs, Markdown, Confluence format
Add dependency
Io.github.swagger2markup swagger2markup 1.3.3
Conversion tool class
Public class SwaggerUtils {private static final String url = "http://127.0.0.1:8080/v2/api-docs";" / * * generate AsciiDocs format document * @ throws MalformedURLException * / public static void generateAsciiDocs () throws MalformedURLException {Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder () .withMa rkupLanguage (MarkupLanguage.ASCIIDOC) .withOutputLanguage (Language.ZH) .withPathsGroupedBy (GroupBy.TAGS) .withGeneratedExamples () .withoutInlineSchema () .build () Swagger2MarkupConverter.from (new URL (url)) .withConfig (config) .build () .toFolder (Paths.get (". / docs/asciidoc/generated")) } / * * generate documents in AsciiDocs format And summarized into a file * @ throws MalformedURLException * / public static void generateAsciiDocsToFile () throws MalformedURLException {Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder () .withMarkupLangu age (MarkupLanguage.ASCIIDOC) .withOutputLanguage (Language.ZH) .withPathsGroupedBy (GroupBy.TAGS) .withGeneratedExamples () .withoutInlineSchema ( ) .build () Swagger2MarkupConverter.from (new URL (url)) .withConfig (config) .build () .toFile (Paths.get (". / docs/asciidoc/generated/all")) } / * generate Markdown format document * @ throws MalformedURLException * / public static void generateMarkdownDocs () throws MalformedURLException {Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder () .wit hMarkupLanguage (MarkupLanguage.MARKDOWN) .withOutputLanguage (Language.ZH) .withPathsGroupedBy (GroupBy.TAGS) .withGeneratedExamples () .withoutInlineSchema () .build () Swagger2MarkupConverter.from (new URL (url)) .withConfig (config) .build () .toFolder (Paths.get (". / docs/markdown/generated")) } / * * generate documents in Markdown format And summarized into a file * @ throws MalformedURLException * / public static void generateMarkdownDocsToFile () throws MalformedURLException {Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder () .withMarkupLa nguage (MarkupLanguage.MARKDOWN) .withOutputLanguage (Language.ZH) .withPathsGroupedBy (GroupBy.TAGS) .withGeneratedExamples () .withoutInlineSchema ( ) .build () Swagger2MarkupConverter.from (new URL (url)) .withConfig (config) .build () .toFile (Paths.get (". / docs/markdown/generated/all")) } / * generate Confluence format document * @ throws MalformedURLException * / public static void generateConfluenceDocs () throws MalformedURLException {Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder () .withMarkupLanguage (MarkupLanguage.CONFLUENCE_MARKUP) .withOutputLanguage (Language.ZH) .withPathsGroupedBy (GroupBy.TAGS) ) .withGeneratedExamples () .withoutInlineSchema () .build () Swagger2MarkupConverter.from (new URL (url)) .withConfig (config) .build () .toFolder (Paths.get (". / docs/confluence/generated")) } / * * generate documents in Confluence format And summarized into a file * @ throws MalformedURLException * / public static void generateConfluenceDocsToFile () throws MalformedURLException {Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder () .withMarkup Language (MarkupLanguage.CONFLUENCE_MARKUP) .withOutputLanguage (Language.ZH) .withPathsGroupedBy (GroupBy.TAGS) .withGeneratedExamples (). WithoutInlineSchema () .build () Swagger2MarkupConverter.from (new URL (url)) .withConfig (config) .build () .toFile (Paths.get (". / docs/confluence/generated/all"));}}
Use the test Controller
@ RestController@RequestMapping ("/ export") @ ApiIgnorepublic class ExportController {@ RequestMapping ("/ ascii") public String exportAscii () throws MalformedURLException {SwaggerUtils.generateAsciiDocs (); return "success";} @ RequestMapping ("/ asciiToFile") public String asciiToFile () throws MalformedURLException {SwaggerUtils.generateAsciiDocsToFile (); return "success" @ RequestMapping ("/ markdown") public String exportMarkdown () throws MalformedURLException {SwaggerUtils.generateMarkdownDocs (); return "success";} @ RequestMapping ("/ markdownToFile") public String exportMarkdownToFile () throws MalformedURLException {SwaggerUtils.generateMarkdownDocsToFile (); return "success" @ RequestMapping ("/ confluence") public String confluence () throws MalformedURLException {SwaggerUtils.generateConfluenceDocs (); return "success";} @ RequestMapping ("/ confluenceToFile") public String confluenceToFile () throws MalformedURLException {SwaggerUtils.generateConfluenceDocsToFile (); return "success";}} 2. Export html, pdf, xml formats
Add dependency
Org.springframework.restdocs spring-restdocs-mockmvc test io.springfox springfox-staticdocs 2.6.1 Org.springframework.boot spring-boot-maven-plugin Io.github.swagger2markup swagger2markup-maven-plugin 1.3.1 http://127.0.0.1:8080/v2/api- Docs. / docs/asciidoc/generated ASCIIDOC Org.asciidoctor asciidoctor-maven-plugin 1.5.3 Org.asciidoctor Asciidoctorj-pdf 1.5.0-alpha.10.1 Org.jruby jruby-complete 1.7.21 . / docs/asciidoc/generated. / docs/asciidoc/html html True book coderay Left 3 True
Html and pdf can be modified here, and files in the corresponding format can be exported through mvn asciidoctor:process-asciidoc.
. / docs/asciidoc/html html
Execute mvn asciidoctor:process-asciidoc and then execute mvn generate-resources to generate xml format files in the targt/generated-docs directory.
At this point, I believe you have a deeper understanding of "how to integrate Swagger2 development API documents". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.