개발

Spring REST Docs Easy: Efficient API Documentation Tool (spring-restdocs-easy)

syaku 2024. 11. 1. 00:57
반응형

Spring REST Docs Easy: Efficient API Documentation Tool

Introduction

Spring REST Docs Easy extends Spring REST Docs to simplify API documentation. It combines test-driven documentation with internationalization support to create accurate and easily manageable API documentation.

https://github.com/syakuis/spring-restdocs-easy

Installation

Gradle

dependencies {
    testImplementation 'io.github.syakuis:spring-restdocs-easy:1.0.0'
}

Practical Usage Examples

1. Basic Configuration

@WebMvcTest(MemberRestController.class)
@AutoConfigureMvcRestDocs
class MemberRestControllerTest {
    @Autowired
    private MockMvc mockMvc;

    @Autowired
    private RestDocs restDocs;

    private final String RESTDOCS_PATH = "members/{method-name}";
}

2. Documenting GET Request (List Retrieval)

@Test
void list() throws Exception {
    mockMvc.perform(get("/members")
            .param("name", "stela")
            .param("age", "10")
            .param("job", "ENGINEER")
            .param("email", "email@email.com")
            .accept(MediaType.APPLICATION_JSON))
        .andExpect(status().isOk())
        .andDo(document(RESTDOCS_PATH,
            // Document request/response headers
            restDocs.headers()
                .add(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON)
                .requestHeaders(),
            restDocs.headers()
                .add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
                .responseHeaders(),

            // Document query parameters
            restDocs.params()
                .add("name", "name parameter")
                .add("age", "{io.github.syakuis.spring.restdocs.easy.examples.adapter.web.controller.model.MemberRequest.age}")
                .add("job", restDocs.generate(Job.class).join())
                .add("email", "{email}")
                .queryParameters(),

            // Document response fields (array response)
            restDocs.generate("[].", MemberResponse.class)
                .addAll("[].locationAddress.", LocationAddress.class)
                .responseFields()
        ));
}

3. Documenting POST Request (Registration)

@Test
void register() throws Exception {
    MemberRequest request = new MemberRequest("John Doe", 30, Job.ACCOUNTANT, 
        "john@example.com", true, List.of("tag1", "tag2"), 
        new LocationAddress("123 Main St", "City", "Country"));

    mockMvc.perform(post("/members")
            .contentType(MediaType.APPLICATION_JSON)
            .header(HttpHeaders.AUTHORIZATION, "")
            .content(objectMapper.writeValueAsString(request)))
        .andExpect(status().isOk())
        .andDo(document(RESTDOCS_PATH,
            // Document request headers
            restDocs.headers()
                .add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
                .add(HttpHeaders.AUTHORIZATION, "{http.headers.authorization.BASIC_AUTHORIZATION}")
                .requestHeaders(),

            // Document request body fields
            restDocs.generate(MemberRequest.class)
                .requestFields()
                .andWithPrefix("locationAddress.", restDocs.generate(LocationAddress.class).toField()),

            // Document response body fields
            restDocs.generate(MemberResponse.class)
                .responseFields()
                .andWithPrefix("locationAddress.", restDocs.generate(LocationAddress.class).toField())
        ));
}

4. Documenting Single Item Retrieval (with Path Variable)

@Test
void view() throws Exception {
    mockMvc.perform(get("/members/{id}", 953))
        .andExpect(status().isOk())
        .andDo(document(RESTDOCS_PATH,
            // Document path variables
            restDocs.params().add("id", "id").pathParameters(),

            // Document response fields
            restDocs.generate(MemberResponse.class)
                .responseFields()
                .andWithPrefix("locationAddress.", 
                    restDocs.generate(LocationAddress.class).toField())
        ));
}

Key Features

1. Comprehensive Documentation Support

  • Request/Response headers (headers())
  • Query parameters (params())
  • Path variables (pathParameters())
  • Request/Response fields (requestFields(), responseFields())
  • Nested objects (andWithPrefix())
  • Array responses ([] notation)

2. Message Source Utilization

  • Direct string descriptions supported
  • Internationalization through message keys ({key} format)
  • Automatic field description references from classes

3. Nested Structure Handling

  • addAll(): Add nested object fields
  • andWithPrefix(): Specify nested field paths
  • Array notation([].) for collection handling

Advantages

  1. Minimizes code duplication
  2. Intuitive API
  3. Flexible documentation options
  4. Maintains Spring REST Docs benefits
  5. Internationalization support

Conclusion

Spring REST Docs Easy extends Spring REST Docs while providing an easy-to-use API. It significantly simplifies documentation tasks, especially for complex APIs with nested object structures or array responses.

반응형