本篇內(nèi)容主要講解“如何實(shí)現(xiàn)集成Swagger2開發(fā)API文檔”,感興趣的朋友不妨來看看。本文介紹的方法操作簡(jiǎn)單快捷,實(shí)用性強(qiáng)。下面就讓小編來帶大家學(xué)習(xí)“如何實(shí)現(xiàn)集成Swagger2開發(fā)API文檔”吧!
10年積累的成都網(wǎng)站設(shè)計(jì)、成都網(wǎng)站制作經(jīng)驗(yàn),可以快速應(yīng)對(duì)客戶對(duì)網(wǎng)站的新想法和需求。提供各種問題對(duì)應(yīng)的解決方案。讓選擇我們的客戶得到更好、更有力的網(wǎng)絡(luò)服務(wù)。我雖然不認(rèn)識(shí)你,你也不認(rèn)識(shí)我。但先網(wǎng)站設(shè)計(jì)后付款的網(wǎng)站建設(shè)流程,更有陽東免費(fèi)網(wǎng)站建設(shè)讓你可以放心的選擇與我們合作。
相信很多后端開發(fā)在項(xiàng)目中都會(huì)碰到要寫 api 文檔,不管是給前端、移動(dòng)端等提供更好的對(duì)接,還是以后為了以后交接方便,都會(huì)要求寫 api 文檔。
而手寫 api 文檔的話有諸多痛點(diǎn):
文檔更新的時(shí)候,需要再次發(fā)送給對(duì)接人
接口太對(duì),手寫文檔很難管理
接口返回的結(jié)果不明確
不能直接在線測(cè)試接口,通常需要使用工具,如 postman 等
Swagger 就很好的解決了這個(gè)問題。
Swagger 是一個(gè)規(guī)范和完整的框架,用于生成、描述、調(diào)用和可視化 RESTful 風(fēng)格的 Web 服務(wù)??傮w目標(biāo)是使客戶端和文件系統(tǒng)作為服務(wù)器以同樣的速度來更新。文件的方法,參數(shù)和模型緊密集成到服務(wù)器端的代碼,允許API來始終保持同步。
官網(wǎng):https://swagger.io
io.springfox springfox-swagger2 2.9.2 io.springfox springfox-swagger-ui 2.9.2
@Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket buildDocket() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(buildApiInf()) //將api的元信息設(shè)置為包含在json resourcelisting響應(yīng)中 //.host("127.0.0.1:8080") //設(shè)置ip和端口,或者域名 .select() //啟動(dòng)用于api選擇的生成器 //.apis(RequestHandlerSelectors.any()) .apis(RequestHandlerSelectors.basePackage("cn.zwqh.springboot.controller"))//指定controller路徑 .paths(PathSelectors.any()).build(); } private ApiInfo buildApiInf() { Contact contact=new Contact("朝霧輕寒","https://www.zwqh.top/","zwqh@clover1314.com"); return new ApiInfoBuilder() .title("Swagger Demo Restful API Docs")//文檔標(biāo)題 .description("Swagger 示例 Restful Api 文檔")//文檔描述 .contact(contact)//聯(lián)系人 .version("1.0")//版本號(hào) //.license("")//更新此API的許可證信息 //.licenseUrl("")//更新此API的許可證Url //.termsOfServiceUrl("")//更新服務(wù)條款URL .build(); } }
@Configuration public class WebMvcConfig extends WebMvcConfigurationSupport { /** * 靜態(tài)資源配置(默認(rèn)) */ @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");// 靜態(tài)資源路徑 registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/"); registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/"); super.addResourceHandlers(registry); } }
如果不添加此靜態(tài)資源配置會(huì)報(bào)錯(cuò),找不到相關(guān)路徑
@ApiModel(value = "UserEntity", description = "用戶對(duì)象") public class UserEntity implements Serializable{ /** * */ private static final long serialVersionUID = 5237730257103305078L; @ApiModelProperty(value ="用戶id",name="id",dataType="Long",required = false,example = "1",hidden = false ) private Long id; @ApiModelProperty(value ="用戶名",name="userName",dataType="String",required = false,example = "關(guān)羽" ) private String userName; @ApiModelProperty(value ="用戶性別",name="userSex",dataType="String",required = false,example = "男" ) 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; } }
@RestController @RequestMapping("/api") @Api(tags = { "接口分組1", "接口分組2" }) public class ApiController { @Autowired private UserDao userDao; @GetMapping("/getAllUser") @ApiOperation(value = "獲取所有用戶", notes = "", httpMethod = "GET", tags = "接口分組3") public ListgetAll() { return userDao.getAll(); } @GetMapping("/getUserById") @ApiOperation(value = "根據(jù)id獲取用戶", notes = "id必傳", httpMethod = "GET") @ApiImplicitParam(name = "id", value = "用戶id",example = "1", required = true, dataType = "long", paramType = "query") public UserEntity getOne(Long id) { return userDao.getOne(id); } @PostMapping("/getUserByNameAndSex") @ApiOperation(value = "根據(jù)name和sex獲取用戶", notes = "", httpMethod = "POST") @ApiImplicitParams({ @ApiImplicitParam(name = "userName", value = "用戶名", example = "關(guān)羽", required = true, dataType = "string", paramType = "query"), @ApiImplicitParam(name = "userSex", value = "用戶性別", example = "男", required = true, dataType = "string", paramType = "query") }) public UserEntity getUserByNameAndSex(String userName, String userSex) { return userDao.getUserByNameAndSex(userName, userSex); } @PostMapping("/insertUser") @ApiOperation(value = "新增用戶", notes = "傳json,數(shù)據(jù)放body", httpMethod = "POST") @ApiImplicitParams({ @ApiImplicitParam(name = "body", value = "用戶對(duì)象json", example = "{userName:'朝霧輕寒',userSex:'男'}", 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 = "修改用戶", notes = "傳json,數(shù)據(jù)放body", httpMethod = "POST") @ApiImplicitParams({ @ApiImplicitParam(name = "body", value = "用戶對(duì)象json", example = "{id:23,userName:'朝霧輕寒',userSex:'女'}", 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 = "刪除用戶", notes = "id必傳", httpMethod = "POST") public String deleteUser(@ApiParam(name = "id", value = "用戶id", required = true) Long id) { userDao.deleteUser(id); return "{code:0,msg:'success'}"; } }
訪問 http://127.0.0.1:8080/swagger-ui.html 進(jìn)行接口在線測(cè)試
用于類,表示標(biāo)識(shí)這個(gè)類是swagger的資源。屬性如下:
tags 表示說明,tags如果有多個(gè)值,會(huì)生成多個(gè)列表
value 表示說明,可以使用tags替代
用于方法,表示一個(gè)http請(qǐng)求的操作。屬性如下:
value 用于方法描述
notes 用于提示內(nèi)容
tags 用于API文檔控制的標(biāo)記列表,視情況而用,可以進(jìn)行獨(dú)立分組
用于方法、參數(shù)、字段說明;表示對(duì)參數(shù)的添加元數(shù)據(jù)。
name 參數(shù)名
value 參數(shù)說明
required 是否必填
用于類,表示對(duì)類進(jìn)行說明,用于參數(shù)用實(shí)體類接受。
value 對(duì)象名
description 描述
用于方法、字段,表示對(duì)model屬性的說明或者數(shù)據(jù)操作更改。
value 字段說明
name 重寫屬性名
dataType 重寫屬性數(shù)據(jù)類型
required 是否必填
example 舉例說明
hidden 隱藏
用于類、方法、方法參數(shù),表示這個(gè)方法或者類被忽略,不在swagger-ui.html上顯示。
用于方法,表示單獨(dú)的請(qǐng)求參數(shù)。
name 參數(shù)名
value 參數(shù)說明
dataType 數(shù)據(jù)類型
paramType 參數(shù)類型
example 舉例說明
用于方法,包含多個(gè) @ApiImplicitParam。
用于類或者方法,描述操作的可能響應(yīng)。
code 響應(yīng)的HTTP狀態(tài)代碼
message 響應(yīng)附帶的可讀消息
用于方法,響應(yīng)頭設(shè)置。
name 響應(yīng)頭名稱
description 頭描述
response 默認(rèn)響應(yīng)類 void
responseContainer 參考ApiOperation中配置
添加依賴
io.github.swagger2markup swagger2markup 1.3.3
轉(zhuǎn)換工具類
public class SwaggerUtils { private static final String url = "http://127.0.0.1:8080/v2/api-docs"; /** * 生成AsciiDocs格式文檔 * @throws MalformedURLException */ public static void generateAsciiDocs() throws MalformedURLException { Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder() .withMarkupLanguage(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")); } /** * 生成AsciiDocs格式文檔,并匯總成一個(gè)文件 * @throws MalformedURLException */ public static void generateAsciiDocsToFile() throws MalformedURLException { Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder() .withMarkupLanguage(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")); } /** * 生成Markdown格式文檔 * @throws MalformedURLException */ public static void generateMarkdownDocs() throws MalformedURLException { Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder() .withMarkupLanguage(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")); } /** * 生成Markdown格式文檔,并匯總成一個(gè)文件 * @throws MalformedURLException */ public static void generateMarkdownDocsToFile() throws MalformedURLException { Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder() .withMarkupLanguage(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")); } /** * 生成Confluence格式文檔 * @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")); } /** * 生成Confluence格式文檔,并匯總成一個(gè)文件 * @throws MalformedURLException */ public static void generateConfluenceDocsToFile() 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() .toFile(Paths.get("./docs/confluence/generated/all")); } }
使用測(cè)試 Controller
@RestController @RequestMapping("/export") @ApiIgnore public 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"; } }
添加依賴
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 和 pdf,通過 mvn asciidoctor:process-asciidoc 可以導(dǎo)出相應(yīng)格式文件
./docs/asciidoc/html html
執(zhí)行 mvn asciidoctor:process-asciidoc 后再執(zhí)行 mvn generate-resources,可在 targt/generated-docs 目錄下生成 xml 格式文件。
到此,相信大家對(duì)“如何實(shí)現(xiàn)集成Swagger2開發(fā)API文檔”有了更深的了解,不妨來實(shí)際操作一番吧!這里是創(chuàng)新互聯(lián)網(wǎng)站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!