您好,登錄后才能下訂單哦!
本篇內(nèi)容主要講解“如何實(shí)現(xiàn)集成Swagger2開(kāi)發(fā)API文檔”,感興趣的朋友不妨來(lái)看看。本文介紹的方法操作簡(jiǎn)單快捷,實(shí)用性強(qiáng)。下面就讓小編來(lái)帶大家學(xué)習(xí)“如何實(shí)現(xiàn)集成Swagger2開(kāi)發(fā)API文檔”吧!
相信很多后端開(kāi)發(fā)在項(xiàng)目中都會(huì)碰到要寫(xiě) api 文檔,不管是給前端、移動(dòng)端等提供更好的對(duì)接,還是以后為了以后交接方便,都會(huì)要求寫(xiě) api 文檔。
而手寫(xiě) api 文檔的話有諸多痛點(diǎn):
文檔更新的時(shí)候,需要再次發(fā)送給對(duì)接人
接口太對(duì),手寫(xiě)文檔很難管理
接口返回的結(jié)果不明確
不能直接在線測(cè)試接口,通常需要使用工具,如 postman 等
Swagger 就很好的解決了這個(gè)問(wèn)題。
Swagger 是一個(gè)規(guī)范和完整的框架,用于生成、描述、調(diào)用和可視化 RESTful 風(fēng)格的 Web 服務(wù)。總體目標(biāo)是使客戶端和文件系統(tǒng)作為服務(wù)器以同樣的速度來(lái)更新。文件的方法,參數(shù)和模型緊密集成到服務(wù)器端的代碼,允許API來(lái)始終保持同步。
官網(wǎng):https://swagger.io
<!--swagger2 --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.9.2</version> </dependency>
@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 List<UserEntity> getAll() { 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'}"; } }
訪問(wèn) http://127.0.0.1:8080/swagger-ui.html 進(jìn)行接口在線測(cè)試
用于類(lèi),表示標(biāo)識(shí)這個(gè)類(lèi)是swagger的資源。屬性如下:
tags 表示說(shuō)明,tags如果有多個(gè)值,會(huì)生成多個(gè)列表
value 表示說(shuō)明,可以使用tags替代
用于方法,表示一個(gè)http請(qǐng)求的操作。屬性如下:
value 用于方法描述
notes 用于提示內(nèi)容
tags 用于API文檔控制的標(biāo)記列表,視情況而用,可以進(jìn)行獨(dú)立分組
用于方法、參數(shù)、字段說(shuō)明;表示對(duì)參數(shù)的添加元數(shù)據(jù)。
name 參數(shù)名
value 參數(shù)說(shuō)明
required 是否必填
用于類(lèi),表示對(duì)類(lèi)進(jìn)行說(shuō)明,用于參數(shù)用實(shí)體類(lèi)接受。
value 對(duì)象名
description 描述
用于方法、字段,表示對(duì)model屬性的說(shuō)明或者數(shù)據(jù)操作更改。
value 字段說(shuō)明
name 重寫(xiě)屬性名
dataType 重寫(xiě)屬性數(shù)據(jù)類(lèi)型
required 是否必填
example 舉例說(shuō)明
hidden 隱藏
用于類(lèi)、方法、方法參數(shù),表示這個(gè)方法或者類(lèi)被忽略,不在swagger-ui.html上顯示。
用于方法,表示單獨(dú)的請(qǐng)求參數(shù)。
name 參數(shù)名
value 參數(shù)說(shuō)明
dataType 數(shù)據(jù)類(lèi)型
paramType 參數(shù)類(lèi)型
example 舉例說(shuō)明
用于方法,包含多個(gè) @ApiImplicitParam。
用于類(lèi)或者方法,描述操作的可能響應(yīng)。
code 響應(yīng)的HTTP狀態(tài)代碼
message 響應(yīng)附帶的可讀消息
用于方法,響應(yīng)頭設(shè)置。
name 響應(yīng)頭名稱
description 頭描述
response 默認(rèn)響應(yīng)類(lèi) void
responseContainer 參考ApiOperation中配置
添加依賴
<!-- swagger2markup 相關(guān)依賴 --> <dependency> <groupId>io.github.swagger2markup</groupId> <artifactId>swagger2markup</artifactId> <version>1.3.3</version> </dependency>
轉(zhuǎn)換工具類(lèi)
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"; } }
添加依賴
<!--離線文檔 --> <dependency> <groupId>org.springframework.restdocs</groupId> <artifactId>spring-restdocs-mockmvc</artifactId> <scope>test</scope> </dependency> <!--springfox-staticdocs 生成靜態(tài)文檔 --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-staticdocs</artifactId> <version>2.6.1</version> </dependency>
<build> <pluginManagement> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> <plugin> <groupId>io.github.swagger2markup</groupId> <artifactId>swagger2markup-maven-plugin</artifactId> <version>1.3.1</version> <configuration> <swaggerInput>http://127.0.0.1:8080/v2/api-docs</swaggerInput> <outputDir>./docs/asciidoc/generated</outputDir> <config> <swagger2markup.markupLanguage>ASCIIDOC</swagger2markup.markupLanguage> </config> </configuration> </plugin> <plugin> <groupId>org.asciidoctor</groupId> <artifactId>asciidoctor-maven-plugin</artifactId> <version>1.5.3</version> <!-- <version>2.0.0-RC.1</version> --> <!-- Include Asciidoctor PDF for pdf generation --> <dependencies> <dependency> <groupId>org.asciidoctor</groupId> <artifactId>asciidoctorj-pdf</artifactId> <version>1.5.0-alpha.10.1</version> </dependency> <dependency> <groupId>org.jruby</groupId> <artifactId>jruby-complete</artifactId> <version>1.7.21</version> </dependency> </dependencies> <configuration> <sourceDirectory>./docs/asciidoc/generated</sourceDirectory> <outputDirectory>./docs/asciidoc/html</outputDirectory> <backend>html</backend> <!-- <outputDirectory>./docs/asciidoc/pdf</outputDirectory> <backend>pdf</backend> --> <headerFooter>true</headerFooter> <doctype>book</doctype> <sourceHighlighter>coderay</sourceHighlighter> <attributes> <!-- 菜單欄在左邊 --> <toc>left</toc> <!-- 多標(biāo)題排列 --> <toclevels>3</toclevels> <!-- 自動(dòng)打數(shù)字序號(hào) --> <sectnums>true</sectnums> </attributes> </configuration> </plugin> </plugins> </pluginManagement> </build>
可以修改此處 html 和 pdf,通過(guò) mvn asciidoctor:process-asciidoc 可以導(dǎo)出相應(yīng)格式文件
<outputDirectory>./docs/asciidoc/html</outputDirectory> <backend>html</backend>
執(zhí)行 mvn asciidoctor:process-asciidoc 后再執(zhí)行 mvn generate-resources,可在 targt/generated-docs 目錄下生成 xml 格式文件。
到此,相信大家對(duì)“如何實(shí)現(xiàn)集成Swagger2開(kāi)發(fā)API文檔”有了更深的了解,不妨來(lái)實(shí)際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。