#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.
-
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. -
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.
-
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.
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.
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.
-
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. -
Add
asciidoctor-maven-plugin
intopom.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. -
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()); } }
-
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.
Open \target\asciidoc\pdf\index.pdf in Pdf viewer, it looks like.
##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:.