博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Build RESTful APIs with Spring MVC: Swagger
阅读量:5771 次
发布时间:2019-06-18

本文共 10730 字,大约阅读时间需要 35 分钟。

  hot3.png

#Visualizes REST APIs with Swagger

Swagger is widely used for visualizing APIs, and with Swagger UI it provides online sandbox for frontend developers.

Visualizes REST APIs

provides Swagger support for Spring based REST APIs.

  1. Add springfox to dependencies.

    io.springfox
    springfox-swagger2
    ${springfox.version}
    io.springfox
    springfox-swagger-ui
    ${springfox.version}

    springfox-swagger-ui provides static Javascript UI for visualizing the Swagger schema definitions.

  2. Add a @Configuration class to enable Swagger.

    @Configuration @EnableSwagger2 public class SwaggerConfig { 	[@Bean](http://my.oschina.net/bean) 	public Docket postsApi() { 		return new Docket(DocumentationType.SWAGGER_2) 				.groupName("public-api") 				.apiInfo(apiInfo()) 				.select() 				.paths(postPaths()) 				.build(); 	} 	private Predicate
    postPaths() { return or( regex("/api/posts.*"), regex("/api/comments.*") ); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("SpringMVC Example API") .description("SpringMVC Example API reference for developers") .termsOfServiceUrl("http://hantsy.blogspot.com") .contact("Hantsy Bai") .license("Apache License Version 2.0") .licenseUrl("https://github.com/springfox/springfox/blob/master/LICENSE") .version("2.0") .build(); } }

    When the application starts up, it will scan all Controllers and generate Swagger schema definition at runtime, Swagger UI will read definitions and render user friendly UI for REST APIs.

  3. View REST APIs in swagger ui.

    Starts up this application via command line.

    mvn tomcat7:run //or mvn spring-boot:run

    Open browser and navigate .

    You will see the screen like the following.

    Swagger-ui

Documents REST APIs

In the above steps, the Swagger schema definition is generated at runtime, you can get the content via link:. You will see the complete Swagger schema definition.

swagger schema

You can save this page content as a json file and upload to and edit it online.

The Swagger schema definition generation will consume lots of system resourcs at runtime.

Combined with Springfox, , and , the Swagger schema definition can be converted to asciidocs, and with asciidoctor-maven-plugin, the asciidocs can be generated into static HTML5 or PDF files.

  1. Add swagger2-markup-maven-plugin into pom.xml file.

    io.github.swagger2markup
    swagger2markup-maven-plugin
    ${swagger2markup.version}
    io.github.swagger2markup
    swagger2markup-import-files-ext
    ${swagger2markup.version}
    io.github.swagger2markup
    swagger2markup-spring-restdocs-ext
    ${swagger2markup.version}
    ${swagger.input}
    ${generated.asciidoc.directory}
    ASCIIDOC
    TAGS
    ${project.basedir}/src/docs/asciidoc/extensions/overview
    ${project.basedir}/src/docs/asciidoc/extensions/definitions
    ${project.basedir}/src/docs/asciidoc/extensions/paths
    ${project.basedir}src/docs/asciidoc/extensions/security/
    ${swagger.snippetOutput.dir}
    true
    test
    convertSwagger2markup

    The convertSwagger2markup goal will convert Swagger schema definition into asciidocs.

  2. Add asciidoctor-maven-plugin into pom.xml file.

    org.asciidoctor
    asciidoctor-maven-plugin
    1.5.3
    org.jruby
    jruby-complete
    ${jruby.version}
    org.asciidoctor
    asciidoctorj-pdf
    ${asciidoctorj-pdf.version}
    ${asciidoctor.input.directory}
    index.adoc
    coderay
    book
    left
    3
    ${generated.asciidoc.directory}
    output-html
    test
    process-asciidoc
    html5
    ${asciidoctor.html.output.directory}
    output-pdf
    test
    process-asciidoc
    pdf
    ${asciidoctor.pdf.output.directory}

    asciidoctor-maven-plugin will generate the asciidocs into HTML5 and PDF files.

  3. Add spring-restdocs support.

    spring-restdocs will generate the sample code snippets from test, which can be combined into the final docs.

    Add related dependencies into pom.xml file.

    io.github.swagger2markup
    swagger2markup-spring-restdocs-ext
    ${swagger2markup.version}
    test
    org.springframework.restdocs
    spring-restdocs-mockmvc
    test

    Write test codes to generate sample code snippets.

    @WebAppConfiguration @RunWith(SpringRunner.class) @SpringBootTest(classes = {Application.class, SwaggerConfig.class}) public class MockMvcApplicationTest { 	String outputDir = System.getProperty("io.springfox.staticdocs.outputDir"); 	String snippetsDir = System.getProperty("io.springfox.staticdocs.snippetsOutputDir"); 	String asciidocOutputDir = System.getProperty("generated.asciidoc.directory"); 	@Rule 	public final JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation(System.getProperty("io.springfox.staticdocs.snippetsOutputDir")); 	@Inject 	private WebApplicationContext context; 	@Inject 	private ObjectMapper objectMapper; 	@Inject 	private PostRepository postRepository; 	private MockMvc mockMvc; 	private Post savedIdentity; 	@Before 	public void setUp() { 		this.mockMvc = webAppContextSetup(this.context) 				.apply(documentationConfiguration(this.restDocumentation)) 				.alwaysDo(document("{method-name}", 						preprocessRequest(prettyPrint()), 						preprocessResponse(prettyPrint()))) 				.build(); 		savedIdentity = postRepository.save(newEntity()); 	} 	@Test 	public void createSpringfoxSwaggerJson() throws Exception { 		//String designFirstSwaggerLocation = Swagger2MarkupTest.class.getResource("/swagger.yaml").getPath(); 		MvcResult mvcResult = this.mockMvc.perform(get("/v2/api-docs") 				.accept(MediaType.APPLICATION_JSON)) 				.andDo( 						SwaggerResultHandler.outputDirectory(outputDir) 						.build() 				) 				.andExpect(status().isOk()) 				.andReturn(); 		//String springfoxSwaggerJson = mvcResult.getResponse().getContentAsString(); 		//SwaggerAssertions.assertThat(Swagger20Parser.parse(springfoxSwaggerJson)).isEqualTo(designFirstSwaggerLocation); 	} 	//    @Test 	//    public void convertToAsciiDoc() throws Exception { 	//        this.mockMvc.perform(get("/v2/api-docs") 	//                .accept(MediaType.APPLICATION_JSON)) 	//                .andDo( 	//                        Swagger2MarkupResultHandler.outputDirectory("src/docs/asciidoc") 	//                        .withExamples(snippetsDir).build()) 	//                .andExpect(status().isOk()); 	//    } 	@Test 	public void getAllPosts() throws Exception { 		this.mockMvc 				.perform( 						get("/api/posts/{id}", savedIdentity.getId()) 						.accept(MediaType.APPLICATION_JSON) 				) 				//.andDo(document("get_a_post", preprocessResponse(prettyPrint()))) 				.andExpect(status().isOk()); 	} 	@Test 	public void getAllIdentities() throws Exception { 		this.mockMvc 				.perform( 						get("/api/posts") 						.accept(MediaType.ALL) 				) 				//.andDo(document("get_all_posts")) 				.andExpect(status().isOk()); 	} 	@Test 	public void createPost() throws Exception { 		this.mockMvc 				.perform( 						post("/api/posts") 						.contentType(MediaType.APPLICATION_JSON) 						.content(newEntityAsJson()) 				) 				//.andDo(document("create_a_new_post")) 				.andExpect(status().isCreated()); 	} 	@Test 	public void updatePost() throws Exception { 		this.mockMvc 				.perform( 						put("/api/posts/{id}", savedIdentity.getId()) 						.contentType(MediaType.APPLICATION_JSON) 						.content(newEntityAsJson()) 				) 				//.andDo(document("update_an_existing_post")) 				.andExpect(status().isNoContent()); 	} 	@Test 	public void deletePost() throws Exception { 		this.mockMvc 				.perform( 						delete("/api/posts/{id}", savedIdentity.getId()) 						.contentType(MediaType.APPLICATION_JSON) 				) 				//.andDo(document("delete_an_existing_post")) 				.andExpect(status().isNoContent()); 	} 	private Post newEntity() { 		Post post = new Post(); 		post.setTitle("test title"); 		post.setContent("test content"); 		return post; 	} 	private String newEntityAsJson() throws JsonProcessingException { 		return objectMapper.writeValueAsString(newEntity()); 	} }
  4. Run mvn clean verify to execute all tests and generate HTML5 and PDF file for the REST APIs.

    Open \target\asciidoc\html\index.html in browser, it looks like.

    html5

    Open \target\asciidoc\pdf\index.pdf in Pdf viewer, it looks like.

    pdf

##Source Code

Check out sample codes from my github account.

git clone https://github.com/hantsy/angularjs-springmvc-sample

Or the Spring Boot version:

git clone https://github.com/hantsy/angularjs-springmvc-sample-boot

Read the live version of thess posts from Gitbook:.

转载于:https://my.oschina.net/hantsy/blog/717745

你可能感兴趣的文章
区块链现状:从谨慎和批判性思维看待它(第二部分)
查看>>
苹果公司透露Siri新发音引擎的内部原理
查看>>
GCM 3.0采用类似方式向Android、iOS和Chrome发送消息
查看>>
如何成为一家敏捷银行
查看>>
Oracle在JavaOne上宣布Java EE 8将会延期至2017年底
查看>>
Javascript 深入浅出原型
查看>>
简单之极,搭建属于自己的Data Mining环境(Spark版本)
查看>>
Ruby 2.5.0概览
查看>>
如何通过解决精益问题提高敏捷团队生产力
查看>>
Apache下.htaccess文件配置及功能介绍
查看>>
Magento XML cheatsheet
查看>>
Egg 2.19.0 发布,阿里开源的企业级 Node.js 框架
查看>>
Kubernetes 弹性伸缩全场景解析 (四)- 让核心组件充满弹性 ...
查看>>
使用MySQLTuner-perl对MySQL进行优化
查看>>
Swoole 4.1.0 正式版发布,支持原生 Redis/PDO/MySQLi 协程化 ...
查看>>
开发网络视频直播系统需要注意的地方
查看>>
haproxy mysql实例配置
查看>>
强化学习的未来— 第一部分
查看>>
TableStore:用户画像数据的存储和查询利器
查看>>
2019 DockerCon 大会即将召开,快来制定您的专属议程吧!
查看>>