Creating API Documentation using Restdocs

Technology: Spring Rest Docs helps you to document RestFul services. It combines hand-written asciidoctor and auto-generated snippets produced with Spring MVC Test.

It helps you to produce documentation that is accurate, concise, and well-structured. This documentation then allows your users to get the information they need with a minimum of fuss.

Building the Sample Application:
Create a sample spring boot application using any of your favourite build tool, or use spring Initializr (https://start.spring.io/) to create a project.

Create a Simple Application:

Create a new controller like below:

@RestController
public class HomeController {
	
	@GetMapping(value="home")
	public Map<String,Object> getHelloResponse()
	{
		return Collections.singletonMap("hello", "rest docs");
	}
}
And Main class will look like below:
@SpringBootApplication
public class Application{

	public static void main(String[] args) {
		SpringApplication.run(Application.class, args);
	}

}

And we will write a sample controller test class for using spring-test module.

@RunWith(SpringRunner.class)
@WebMvcTest(controllers=HomeController.class)
public class HomeControllerTest {
	@Autowired
	private MockMvc mockMvc;
	
	@Test
	public void shouldReturnMessage() throws Exception
	{
		this.mockMvc.perform(get("/home")).andDo(print()).andExpect(status().isOk()).andExpect(content().string(containsString("rest docs")));
	}
}

Adding RestDocs Dependency:

Add the below dependency into pom.xml file.

<dependency>
	<groupId>org.springframework.restdocs</groupId>
	<artifactId>spring-restdocs-mockmvc</artifactId>
	<scope>test</scope>
</dependency>

Creating Snippets for Documentation

@AutoConfigureRestDocs annontation used to bootstrap the spring Restdocs library. Provide the outputDir attribute so that the snippets will create in specified folder. The default folder for creating the snippets is “target/generated-snippets”.

If we want to customize any of the default settings or default way of generating the snippets, then we can customize the library using RestDocsMockMvcConfigurationCustomizer interface, and override the customize method.

After adding @AutoConfigureRestDocs annotation the class will look like this:

@RunWith(SpringRunner.class)
@WebMvcTest(controllers=HomeController.class)
@AutoConfigureRestDocs(outputDir="target/snippets")
public class HomeControllerTest {
	@Autowired
	private MockMvc mockMvc;
	
	@Test
	public void shouldReturnMessage() throws Exception
	{
		this.mockMvc.perform(get("/home")).andDo(print()).andExpect(status().isOk()).andExpect(content().string(containsString("rest docs"))).andDo(document("home"));
	}
}

documents is the method to Document API with given identifier. After running above test, with given identifier name folder will create in given outputDir folder.

The default are in Asciidoor format for HTTP request, and HTTP-Response, and also it will include httpie and curl command line tools for invoking Rest calls.

If we update the test to check for fields in JSON, then test class is

@Test
	public void shouldReturnMessage() throws Exception {
		this.mockMvc.perform(get("/home")).andDo(print()).andExpect(status().isOk())
				.andExpect(content().string(containsString("rest docs"))).andDo(document("home",
						responseFields(fieldWithPath("hello").description("rest docs"))));
	}

responseFields and fieldsWithPath are used to test the response JSON, validate the against the key and value.

Using the Snippets:
We will use these snippets to create documentation page.
We will use asciidoor-maven-plugin for generating the html documentation, for that we need to provide the request and response asciidoor files (which we generated earlier).

Now lets create index.adoc in src/main/asciidoc folder with below content.

= Getting Started With Spring REST Docs

This is an example output for a Java software development service running at http://localhost:8080:

.request
include::{snippets}/home/http-request.adoc[]

.response
include::{snippets}/home/http-response.adoc[]

As you can see the format is very simple, and in fact you always get the same message.

The main feature of this is that it includes 2 of the snippets, using the Asciidoctor include directive (the colons and the trailing brackets tell the parser to do something special on those lines). Notice that the path to the included snippets is expressed as a placeholder – an “attribute” in Asciidoctor – called {snippets}. The only other markup in this simple case is the “=” at the top, which is a level 1 section heading, and the “.” before the captions (“request” and “response”) on the snippets.

if multiple request and response are there we can repeat the request and response section many times.

Maven plugin Configuration:

<plugin>
	<groupId>org.asciidoctor</groupId>
	<artifactId>asciidoctor-maven-plugin</artifactId>
	<executions>
		<execution>
			<id>generate-docs</id>
			<phase>prepare-package</phase>
			<goals>
				<goal>process-asciidoc</goal>
			</goals>
			<configuration>
				<sourceDocumentName>index.adoc</sourceDocumentName>
				<backend>html</backend>
				<attributes>
					<snippets>${project.build.directory}/snippets</snippets>
				</attributes>
			</configuration>
		</execution>
	</executions>
</plugin>

As the phase is prepare-package, then invoke mvnw package then it will create folder “generated-docs” in build folder.
It contains HTML file with rest api documentation.

Conclusion: We learned that way to generate the documentation using RestDocs and Asciidoctor maven plugin, it will publish the HTML documentation for unit-tested spring controller, and it will be always updated, as tests will update if any of the changes to controller classes.

Leave a Reply

Your email address will not be published.




*

code