Pro Tips — Automated API Documentation with Spring REST Docs
Swagger documentation drifts from the actual API over time. Spring REST Docs generates documentation snippets only when the MockMvc test passes — guaranteeing that tests and API docs are always in sync.
1. Dependencies
testImplementation 'org.springframework.restdocs:spring-restdocs-mockmvc'
asciidoctorExt 'org.springframework.restdocs:spring-restdocs-asciidoctor'
2. Generating Documentation Snippets in Tests
@WebMvcTest(UserController.class)
@AutoConfigureRestDocs(outputDir = "build/generated-snippets")
class UserControllerDocTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private UserService userService;
@Test
void document_get_user_api() throws Exception {
given(userService.getUser(1L)).willReturn(new UserDto(1L, "John Doe", "john@test.com"));
mockMvc.perform(get("/api/users/{id}", 1L).accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andDo(document("get-user",
pathParameters(
parameterWithName("id").description("User identifier")
),
responseFields(
fieldWithPath("id").description("User ID"),
fieldWithPath("name").description("User name"),
fieldWithPath("email").description("Email address")
)
));
}
}
When tests run, build/generated-snippets/get-user/ is populated with auto-generated Asciidoc files.
3. Assembling the Final API Doc (index.adoc)
= API Reference
:toc: left
== User API
=== Get User by ID
==== HTTP Request
include::{snippets}/get-user/http-request.adoc[]
==== Path Parameters
include::{snippets}/get-user/path-parameters.adoc[]
==== HTTP Response
include::{snippets}/get-user/http-response.adoc[]
==== Response Fields
include::{snippets}/get-user/response-fields.adoc[]
Running ./gradlew asciidoctor produces a polished, shareable HTML API reference.