### HTTP Request Example Source: https://github.com/spring-projects/spring-restdocs/blob/main/spring-restdocs-asciidoctor/src/test/resources/operations/multiple-snippets.html Shows the raw HTTP request format for a GET request to the root path. This is helpful for understanding the underlying protocol. ```http GET / HTTP/1.1 Host: localhost:8080 ``` -------------------------------- ### Curl Request Example Source: https://github.com/spring-projects/spring-restdocs/blob/main/spring-restdocs-asciidoctor/src/test/resources/operations/snippet-in-section.html This snippet shows a basic curl command to make a GET request to a local server. It includes the -i flag to show response headers. ```curl $ curl 'http://localhost:8080/' -i ``` -------------------------------- ### Build the Project with Gradle Source: https://github.com/spring-projects/spring-restdocs/blob/main/CONTRIBUTING.md Use this command to build the entire Spring REST Docs project from source. Ensure you have Java 17 or later installed. ```bash ./gradlew build ``` -------------------------------- ### WebTestClient Test Setup (JUnit 5) Source: https://context7.com/spring-projects/spring-restdocs/llms.txt Configure WebTestClient with documentationConfiguration for reactive Spring WebFlux applications. Add spring-restdocs-webtestclient dependency. ```java import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.context.ApplicationContext; import org.springframework.restdocs.RestDocumentationContextProvider; import org.springframework.restdocs.RestDocumentationExtension; import org.springframework.test.web.reactive.server.WebTestClient; import static org.springframework.restdocs.webtestclient.WebTestClientRestDocumentation.documentationConfiguration; @ExtendWith({RestDocumentationExtension.class, SpringExtension.class}) public class ReactiveApiDocumentationTests { private WebTestClient webTestClient; @BeforeEach void setUp(ApplicationContext applicationContext, RestDocumentationContextProvider restDocumentation) { this.webTestClient = WebTestClient .bindToApplicationContext(applicationContext) .configureClient() .filter(documentationConfiguration(restDocumentation)) .build(); } } ``` -------------------------------- ### GET / Source: https://github.com/spring-projects/spring-restdocs/blob/main/spring-restdocs-asciidoctor/src/test/resources/operations/all-snippets.html This endpoint retrieves information. It is a simple GET request to the root path. ```APIDOC ## GET / ### Description This endpoint retrieves information. It is a simple GET request to the root path. ### Method GET ### Endpoint / ### Response #### Success Response (200) - **a** (Object) - one - **a.b** (Number) - two - **a.c** (String) - three ``` -------------------------------- ### Configure MockMvc and WebTestClient for TestNG Source: https://github.com/spring-projects/spring-restdocs/blob/main/spring-restdocs-docs/src/docs/antora/modules/tutorial/pages/getting-started/index.adoc Integrate `ManualRestDocumentation` with TestNG by calling `beforeTest` and `afterTest` methods. This setup is crucial for both MockMvc and WebTestClient test configurations. ```java include-code::mockmvc/ExampleApplicationTestNgTests[] ``` ```java include-code::webtestclient/ExampleApplicationTestNgTests[] ``` -------------------------------- ### Per-Test Request and Response Preprocessing with MockMvc Source: https://github.com/spring-projects/spring-restdocs/blob/main/spring-restdocs-docs/src/docs/antora/modules/reference/pages/customizing-requests-and-responses.adoc Apply request and response preprocessors on a per-test basis when using MockMvc. This example removes the 'Foo' header from requests and pretty-prints response bodies. ```java given(this.spec).filter(document("index", preprocessRequest(removeHeaders("Foo")), preprocessResponse(prettyPrint()))) .when() .get("/test") .then() .assertThat() .statusCode(is(200)); ``` -------------------------------- ### Customize Documented URIs for MockMvc Source: https://context7.com/spring-projects/spring-restdocs/llms.txt Override the default documented URI scheme, host, and port for MockMvc by configuring the `MockMvcRestDocumentationConfigurer` within the `documentationConfiguration`. This example sets the scheme to 'https', host to 'api.example.com', and port to 443. ```java // MockMvc: change documented URIs to https://api.example.com @BeforeEach void setUp(WebApplicationContext ctx, RestDocumentationContextProvider restDocumentation) { this.mockMvc = MockMvcBuilders.webAppContextSetup(ctx) .apply(documentationConfiguration(restDocumentation) .uris() .withScheme("https") .withHost("api.example.com") .withPort(443)) .build(); } ``` -------------------------------- ### Generate Eclipse Project Metadata Source: https://github.com/spring-projects/spring-restdocs/blob/main/CONTRIBUTING.md Run this Gradle task to generate the necessary project and classpath metadata for importing into Eclipse. This simplifies IDE setup. ```bash ./gradlew eclipse ``` -------------------------------- ### Documenting an Array of Books Payload Source: https://github.com/spring-projects/spring-restdocs/blob/main/spring-restdocs-docs/src/docs/antora/modules/reference/pages/documenting-your-api/request-response-payloads.adoc Provides an example of a JSON payload containing an array of book objects, each with a title and author. ```json [{ "title": "Pride and Prejudice", "author": "Jane Austen" }, { "title": "To Kill a Mockingbird", "author": "Harper Lee" }] ``` -------------------------------- ### MockMvc Parameterized Output Directory Source: https://github.com/spring-projects/spring-restdocs/blob/main/spring-restdocs-docs/src/docs/antora/modules/how-to/pages/parameterizing-the-output-directory.adoc Configure MockMvc to use a parameterized output directory for documentation snippets. This setup is often used in a `@BeforeEach` method to apply the configuration to all tests within a class. ```java import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document; import static org.springframework.restdocs.operation.preprocess.Preprocessors.*; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.restdocs.RestDocumentationExtension; import org.springframework.test.web.servlet.MockMvc; @WebMvcTest @AutoConfigureRestDocs(uriScheme = "http", uriHost = "docs.example.com") @ExtendWith(RestDocumentationExtension.class) class ParameterizedOutputMockMvcDocumentation { @Autowired private MockMvc mockMvc; @BeforeEach void setUpRestDocs() { this.mockMvc .document( defaultOptions() .withPathGenerator( request -> String.format("%s/%s", request.getMethod(), request.getName())); } @Test void creatingANote() { // ... } @Test void gettingANote() { // ... } } ``` -------------------------------- ### Custom Snippet Example Source: https://github.com/spring-projects/spring-restdocs/blob/main/spring-restdocs-asciidoctor/src/test/resources/operations/all-snippets.html This represents a custom snippet that can be defined and used within the documentation. It includes non-ASCII characters. ```text mycustomsnippet-äöü ``` -------------------------------- ### WebTestClient Parameterized Output Directory Source: https://github.com/spring-projects/spring-restdocs/blob/main/spring-restdocs-docs/src/docs/antora/modules/how-to/pages/parameterizing-the-output-directory.adoc Configure WebTestClient to use a parameterized output directory for documentation snippets. This setup is often used in a `@BeforeEach` method to apply the configuration to all tests within a class. ```java import static org.springframework.restdocs.webtestclient.WebTestClientRestDocumentation.document; import static org.springframework.restdocs.operation.preprocess.Preprocessors.*; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.restdocs.RestDocumentationExtension; import org.springframework.test.web.reactive.server.WebTestClient; @SpringBootTest @AutoConfigureRestDocs(uriScheme = "http", uriHost = "docs.example.com") @ExtendWith(RestDocumentationExtension.class) class ParameterizedOutputWebTestClientDocumentation { private WebTestClient webTestClient; @BeforeEach void setUp(RestDocumentationExtension restDocumentationExtension) { this.webTestClient = WebTestClient.bindToServer() .baseUrl("http://localhost:8080") .filter(restDocumentationExtension.documentationConfiguration(new FormatConfigurer())) .build(); } @Test void creatingANote() { this.webTestClient .post() .uri("/notes") .exchange() .expectStatus() .isCreated() .expectBody() // .consumeWith(document( defaultOptions() .withPathGenerator( request -> String.format("%s/%s", request.getMethod(), request.getName())))); } @Test void gettingANote() { // ... } } ``` -------------------------------- ### JUnit 5 MockMvc Test Setup with Spring REST Docs Source: https://context7.com/spring-projects/spring-restdocs/llms.txt Set up MockMvc for API documentation tests using JUnit 5. Apply RestDocumentationExtension and configure MockMvc with documentationConfiguration in a @BeforeEach method. Snippets are automatically written to the configured output directory. ```java import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.restdocs.RestDocumentationContextProvider; import org.springframework.restdocs.RestDocumentationExtension; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration; @ExtendWith({RestDocumentationExtension.class, SpringExtension.class}) public class ApiDocumentationTests { private MockMvc mockMvc; @BeforeEach void setUp(WebApplicationContext webApplicationContext, RestDocumentationContextProvider restDocumentation) { this.mockMvc = MockMvcBuilders .webAppContextSetup(webApplicationContext) .apply(documentationConfiguration(restDocumentation)) .build(); } } ``` -------------------------------- ### Configure Default Snippets with MockMvc Source: https://context7.com/spring-projects/spring-restdocs/llms.txt Configure MockMvc to produce only specific snippets by default, reducing output when only certain types are needed. This setup is typically done in a `@BeforeEach` method. ```java import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration; import static org.springframework.restdocs.templates.TemplateFormats.asciidoctor; // Produce only the curl-request snippet by default (instead of all six) @BeforeEach void setUp(WebApplicationContext ctx, RestDocumentationContextProvider restDocumentation) { this.mockMvc = MockMvcBuilders.webAppContextSetup(ctx) .apply(documentationConfiguration(restDocumentation) .snippets() .withDefaults(curlRequest())) .build(); } ``` -------------------------------- ### Use Relaxed Mode for Partial Documentation Source: https://context7.com/spring-projects/spring-restdocs/llms.txt Prefix snippet methods with `relaxed` to suppress failures for undocumented elements, useful for documenting subsets of large payloads or gradually building documentation. This example shows partial response field and query parameter documentation. ```java import static org.springframework.restdocs.payload.PayloadDocumentation.*; import static org.springframework.restdocs.request.RequestDocumentation.*; import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document; import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.get; @Test void relaxedDocumentationExample() throws Exception { // Only document a subset of fields — undocumented fields will NOT cause failure this.mockMvc.perform(get("/user/5").accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andDo(document("user-partial", relaxedResponseFields( fieldWithPath("contact.email").description("The user's email address")))); // Only document a subset of query parameters this.mockMvc.perform(get("/users?page=1&per_page=20&sort=name&order=asc")) .andExpect(status().isOk()) .andDo(document("users-partial", relaxedQueryParameters( parameterWithName("page").description("The page to retrieve")))); } ``` -------------------------------- ### Customize Documented Base URI for WebTestClient Source: https://context7.com/spring-projects/spring-restdocs/llms.txt For WebTestClient, customize the documented base URI by using the `baseUrl()` method on the client builder when configuring the `WebTestClient`. This example sets the base URI to 'https://api.example.com'. ```java // WebTestClient: change documented base URI @BeforeEach void setUp(ApplicationContext ctx, RestDocumentationContextProvider restDocumentation) { this.webTestClient = WebTestClient.bindToApplicationContext(ctx) .configureClient() .baseUrl("https://api.example.com") // sets documented base URI .filter(documentationConfiguration(restDocumentation)) .build(); } ``` -------------------------------- ### Build Sample Projects with Gradle Source: https://github.com/spring-projects/spring-restdocs/blob/main/CONTRIBUTING.md Execute this command to build all sample projects included in Spring REST Docs. This is useful for testing sample code. ```bash ./gradlew buildSamples ``` -------------------------------- ### Accessing Constraint Descriptions Source: https://github.com/spring-projects/spring-restdocs/blob/main/spring-restdocs-docs/src/docs/antora/modules/reference/pages/documenting-your-api/constraints.adoc Use `ConstraintDescriptions` to retrieve descriptions of a class's constraints. This example shows how to get descriptions for the `name` property, which has `NotNull` and `Size` constraints. ```java ConstraintDescriptions constraintDescriptions = new ConstraintDescriptions(UserInput.class); // Get descriptions for the 'name' property's constraints Set description = constraintDescriptions.descriptionsFor("name"); ``` -------------------------------- ### Configure Gradle for Documentation Generation Source: https://github.com/spring-projects/spring-restdocs/blob/main/spring-restdocs-docs/src/docs/antora/modules/tutorial/pages/getting-started/index.adoc Configure the `bootJar` task to depend on `asciidoctor` and copy the generated documentation into the jar's `static/docs` directory. ```gradle bootJar { dependsOn asciidoctor from ("${asciidoctor.outputDir}") { into 'static/docs' } } ``` -------------------------------- ### Root Endpoint Source: https://github.com/spring-projects/spring-restdocs/blob/main/spring-restdocs-asciidoctor/src/test/resources/operations/multiple-snippets.html This endpoint serves as the root of the API, typically used for basic health checks or as a starting point. ```APIDOC ## GET / ### Description This is the root endpoint of the API. ### Method GET ### Endpoint / ### Request Example ```bash $ curl 'http://localhost:8080/' -i ``` ### Response #### Success Response (200) This section is not explicitly documented in the source. ``` -------------------------------- ### Configure Maven for Documentation Generation Source: https://github.com/spring-projects/spring-restdocs/blob/main/spring-restdocs-docs/src/docs/antora/modules/tutorial/pages/getting-started/index.adoc Configure the `asciidoctor-maven-plugin` and `maven-resources-plugin` to generate and copy documentation to the build output. Ensure the resource plugin runs after the Asciidoctor plugin. ```xml org.asciidoctor asciidoctor-maven-plugin maven-resources-plugin copy-resources prepare-package copy-resources ${project.build.outputDirectory}/static/docs ${project.build.directory}/generated-docs ``` -------------------------------- ### Configure Global Preprocessors for All Tests Source: https://context7.com/spring-projects/spring-restdocs/llms.txt Configure global request and response preprocessors in a `@BeforeEach` method using `documentationConfiguration`. This applies `modifyHeaders` and `prettyPrint` to all tests within the scope of the configuration. ```java import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document; import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.get; import static org.springframework.restdocs.operation.preprocess.Preprocessors.*; // Global preprocessors applied to every test — configure in @BeforeEach @BeforeEach void setUp(WebApplicationContext ctx, RestDocumentationContextProvider restDocumentation) { this.mockMvc = MockMvcBuilders.webAppContextSetup(ctx) .apply(documentationConfiguration(restDocumentation) .operationPreprocessors() .withRequestDefaults(modifyHeaders().remove("Foo")) // <1> .withResponseDefaults(prettyPrint())) // <2> .build(); } ``` -------------------------------- ### Documenting Query Parameters with queryParameters() Source: https://context7.com/spring-projects/spring-restdocs/llms.txt Use `queryParameters()` with `parameterWithName()` to document URL query string parameters. Ensure parameters are present in the URL or specified via `.queryParam()`. ```java import static org.springframework.restdocs.request.RequestDocumentation.*; import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document; import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.get; @Test void queryParametersExample() throws Exception { this.mockMvc.perform(get("/users?page=2&per_page=100")) .andExpect(status().isOk()) .andDo(document("users", queryParameters( parameterWithName("page").description("The page to retrieve"), parameterWithName("per_page").description("Entries per page")))); // Writes: users/query-parameters.adoc } ``` -------------------------------- ### Documenting Wildcard Field Paths Source: https://github.com/spring-projects/spring-restdocs/blob/main/spring-restdocs-docs/src/docs/antora/modules/reference/pages/documenting-your-api/request-response-payloads.adoc Shows how to use the wildcard '*' to document fields within objects where the key names are not known or vary. Useful for documenting nested structures with dynamic keys. ```json { "users":{ "ab12cd34":{ "role": "Administrator" }, "12ab34cd":{ "role": "Guest" } } } ``` -------------------------------- ### Documenting an Array of Books with Reused Descriptors (MockMvc) Source: https://github.com/spring-projects/spring-restdocs/blob/main/spring-restdocs-docs/src/docs/antora/modules/reference/pages/documenting-your-api/request-response-payloads.adoc Illustrates documenting an array of book objects by reusing field descriptors. The `[]` prefix is automatically handled when documenting arrays. ```java restDocumentation.document( restFields( fieldWithPath("[]").description("An array of books") ), restFields( BookPayload.TITLE, BookPayload.AUTHOR ) ); ``` -------------------------------- ### Documenting API Operations (MockMvc) Source: https://context7.com/spring-projects/spring-restdocs/llms.txt Use document("operation-name") with MockMvc's andDo() to capture requests/responses and write default snippets. Ensure MockMvcRestDocumentation.document and RestDocumentationRequestBuilders are imported. ```java // MockMvc import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document; import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @Test void indexExample() throws Exception { this.mockMvc.perform(get("/").accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andDo(document("index")); // Writes: build/generated-snippets/index/curl-request.adoc // build/generated-snippets/index/http-request.adoc // build/generated-snippets/index/http-response.adoc etc. } ``` -------------------------------- ### Maven Build Configuration for Spring REST Docs Source: https://github.com/spring-projects/spring-restdocs/blob/main/spring-restdocs-docs/src/docs/antora/modules/tutorial/pages/getting-started/index.adoc Configure Maven to include `spring-restdocs-mockmvc` for testing and the `asciidoctor-maven-plugin` with `spring-restdocs-asciidoctor` for documentation generation. The `prepare-package` phase ensures documentation is included in the build. ```xml org.springframework.restdocs spring-restdocs-mockmvc {project-version} test org.asciidoctor asciidoctor-maven-plugin 3.2.0 generate-docs prepare-package process-asciidoc html book org.springframework.restdocs spring-restdocs-asciidoctor {project-version} ``` -------------------------------- ### Format Table Columns Source: https://github.com/spring-projects/spring-restdocs/blob/main/spring-restdocs-docs/src/docs/antora/modules/reference/pages/working-with-asciidoctor.adoc Customize the appearance of tables within snippets by using Asciidoctor's `cols` attribute to specify column widths. This example splits the table width across two columns, with the second being three times as wide as the first. ```asciidoc [cols="1,3"] \include::{snippets}/index/links.adoc[] ``` -------------------------------- ### Documenting Array Elements with WebTestClient Source: https://github.com/spring-projects/spring-restdocs/blob/main/spring-restdocs-docs/src/docs/antora/modules/reference/pages/documenting-your-api/request-response-payloads.adoc Demonstrates how to document individual elements within an array using WebTestClient. It shows how to reuse existing descriptors for array elements. ```java webTestClient.get().uri("/documents/1") .exchange() .expectStatus().isOk() .expectBody(DocumentedField.class) .consumeWith(document("array-descriptor-reuse", responseFields( fieldWithPath("title").description("The title of the document"), fieldWithPath("author").description("The author of the document")))); ``` -------------------------------- ### Configure MockMvc with RestDocumentationConfigurer Source: https://github.com/spring-projects/spring-restdocs/blob/main/spring-restdocs-docs/src/docs/antora/modules/tutorial/pages/getting-started/index.adoc Configure the `MockMvc` instance using `MockMvcRestDocumentationConfigurer`. Obtain the configurer from `MockMvcRestDocumentation.documentationConfiguration()`. ```java include-code::mockmvc/ExampleApplicationTests[] ``` -------------------------------- ### Documenting Query Parameters with MockMvc Source: https://github.com/spring-projects/spring-restdocs/blob/main/spring-restdocs-docs/src/docs/antora/modules/reference/pages/documenting-your-api/query-parameters.adoc Use `queryParameters` to document query parameters for MockMvc requests. Parameters can be included in the URL or specified using `queryParam` or `queryParams`. ```java given() .mockMvc(this.mockMvc) .param("page", "0") .param("per_page", "20") .when() .get("/users?page=0&per_page=20") .then() .extract() .documentationSequence() .apply( queryParameters( parameterWithName("page").description("The page of results to return."), parameterWithName("per_page").description("The number of items to return per page.") ) ); ``` -------------------------------- ### Documenting HAL Links with MockMvc Source: https://github.com/spring-projects/spring-restdocs/blob/main/spring-restdocs-docs/src/docs/antora/modules/reference/pages/documenting-your-api/hypermedia.adoc Configure Spring REST Docs to produce a snippet describing HAL format links using MockMvc. Uses the static `halLinks` method. ```java given(this.restDocumentation) .upon(halLinks()) .withHypermedia(linksTo(MyResource.class, "my-resource")) .and(linkWithRel("alpha").description("The alpha link")) .and(linkWithRel("bravo").description("The bravo link")) .when(this.mockMvc.perform(get("/my-resource"))) .then(document("hypermedia/links")); ``` -------------------------------- ### Documenting HTTP Headers (MockMvc) Source: https://context7.com/spring-projects/spring-restdocs/llms.txt Use requestHeaders() and responseHeaders() with headerWithName() to document required or present headers. The test fails if a documented header is absent. Ensure HeaderDocumentation and MockMvcRestDocumentation are imported. ```java import static org.springframework.restdocs.headers.HeaderDocumentation.*; import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document; import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.get; @Test void headersExample() throws Exception { this.mockMvc.perform(get("/people") .header("Authorization", "Basic dXNlcjpzZWNyZXQ=")) .andExpect(status().isOk()) .andDo(document("headers", requestHeaders( headerWithName("Authorization").description("Basic auth credentials")), responseHeaders( headerWithName("X-RateLimit-Limit") .description("Total requests permitted per period"), headerWithName("X-RateLimit-Remaining") .description("Remaining requests in current period"), headerWithName("X-RateLimit-Reset") .description("Time at which the rate limit period resets")))); // Writes: headers/request-headers.adoc, headers/response-headers.adoc } ``` -------------------------------- ### Invoke Service and Document with MockMvc Source: https://github.com/spring-projects/spring-restdocs/blob/main/spring-restdocs-docs/src/docs/antora/modules/tutorial/pages/getting-started/index.adoc Use MockMvc to invoke a RESTful service and generate documentation snippets. This involves calling the service, asserting the response, and documenting the call using `MockMvcRestDocumentation.document`. ```java include-code::mockmvc/InvokeService[] ``` -------------------------------- ### Documenting API Operations (WebTestClient) Source: https://context7.com/spring-projects/spring-restdocs/llms.txt Use document("operation-name") with WebTestClient's consumeWith() to capture requests/responses and write default snippets. Ensure WebTestClientRestDocumentation.document is imported. ```java // WebTestClient import static org.springframework.restdocs.webtestclient.WebTestClientRestDocumentation.document; @Test void indexExample() { this.webTestClient.get().uri("/") .accept(MediaType.APPLICATION_JSON) .exchange() .expectStatus().isOk() .expectBody() .consumeWith(document("index")); } ``` -------------------------------- ### Configure Default Preprocessors with MockMvc Source: https://github.com/spring-projects/spring-restdocs/blob/main/spring-restdocs-docs/src/docs/antora/modules/reference/pages/configuration/default-preprocessors.adoc Use this snippet to apply a request preprocessor that removes the header named `Foo` and a response preprocessor that pretty prints its content when using MockMvc. ```java given(this.webTestClient) .filter(removeHeadersNamed("Foo")) .filter(prettyPrint()) .when() .get("/test") .then() .assertThat(document("custom-default-operation-preprocessors")); ``` -------------------------------- ### Gradle Build Configuration for Spring REST Docs Source: https://context7.com/spring-projects/spring-restdocs/llms.txt Configure build.gradle to apply the Asciidoctor plugin, declare a custom asciidoctorExt configuration, and link test and asciidoctor tasks using a shared snippets output directory. ```groovy // build.gradle plugins { id "org.asciidoctor.jvm.convert" version "4.0.5" } asciidoctorj { version = "3.0.0" } configurations { asciidoctorExt } dependencies { asciidoctorExt 'org.springframework.restdocs:spring-restdocs-asciidoctor:4.0.1' testImplementation 'org.springframework.restdocs:spring-restdocs-mockmvc:4.0.1' } ext { snippetsDir = file('build/generated-snippets') } tasks.named("test") { outputs.dir snippetsDir } tasks.named("asciidoctor") { inputs.dir snippetsDir configurations 'asciidoctorExt' dependsOn test } ``` -------------------------------- ### Documenting Hypermedia Links with links() Source: https://context7.com/spring-projects/spring-restdocs/llms.txt Use `links()` with `linkWithRel()` to document HATEOAS/hypermedia links. Supports Atom and HAL formats automatically. The test fails for undocumented links. ```java import static org.springframework.restdocs.hypermedia.HypermediaDocumentation.*; import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document; import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.get; // Response: { "_links": { "self": {...}, "alpha": {...}, "bravo": {...} } } @Test void hypermediaExample() throws Exception { this.mockMvc.perform(get("/").accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andDo(document("index", links( linkWithRel("alpha").description("Link to the alpha resource"), linkWithRel("bravo").description("Link to the bravo resource")))); // Writes: index/links.adoc // Explicitly specify HAL format when content type differs from application/hal+json this.mockMvc.perform(get("/").accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andDo(document("index-hal", links(halLinks(), linkWithRel("self").description("Self link"), linkWithRel("users").description("Link to the users resource")))); } ``` -------------------------------- ### Documenting Query Parameters Source: https://context7.com/spring-projects/spring-restdocs/llms.txt Use `queryParameters()` with `parameterWithName()` to document URL query string parameters. These parameters can be placed directly in the URL or specified using `.queryParam()` / `.queryParams()` on the request builder. ```APIDOC ## GET /users ### Description Retrieves a list of users with pagination support. ### Method GET ### Endpoint /users ### Query Parameters - **page** (string) - Required - The page to retrieve - **per_page** (string) - Required - Entries per page ### Request Example ```java this.mockMvc.perform(get("/users?page=2&per_page=100")) .andExpect(status().isOk()) .andDo(document("users/query-parameters", queryParameters( parameterWithName("page").description("The page to retrieve"), parameterWithName("per_page").description("Entries per page")))); ``` ### Response #### Success Response (200) - **[Array of User objects]** - Description of the user array ``` -------------------------------- ### Documenting Query Parameters with WebTestClient Source: https://github.com/spring-projects/spring-restdocs/blob/main/spring-restdocs-docs/src/docs/antora/modules/reference/pages/documenting-your-api/query-parameters.adoc Use `queryParameters` to document query parameters for WebTestClient requests. Parameters can be included in the URL or specified using `queryParam` or `queryParams`. ```java given() .webTestClient(this.webTestClient) .param("page", "0") .param("per_page", "20") .when() .get("/users?page=0&per_page=20") .then() .extract() .documentationSequence() .apply( queryParameters( parameterWithName("page").description("The page of results to return."), parameterWithName("per_page").description("The number of items to return per page.") ) ); ``` -------------------------------- ### Gradle Build Configuration for Spring REST Docs Source: https://github.com/spring-projects/spring-restdocs/blob/main/spring-restdocs-docs/src/docs/antora/modules/tutorial/pages/getting-started/index.adoc Configure Gradle with the Asciidoctor plugin, specifying AsciidoctorJ version, and adding `spring-restdocs-asciidoctor` to `asciidoctorExt` and `spring-restdocs-mockmvc` to `testImplementation`. It also sets up `snippetsDir` and task dependencies for incremental builds. ```gradle plugins { id "org.asciidoctor.jvm.convert" version "4.0.5" } asciidoctorj { version = "3.0.0" } configurations { asciidoctorExt } dependencies { asciidoctorExt 'org.springframework.restdocs:spring-restdocs-asciidoctor:{project-version}' testImplementation 'org.springframework.restdocs:spring-restdocs-mockmvc:{project-version}' } ext { snippetsDir = file('build/generated-snippets') } tasks.named("test") { outputs.dir snippetsDir } tasks.named("asciidoctor") { inputs.dir snippetsDir configurations 'asciidoctorExt' dependsOn test } ``` -------------------------------- ### Documenting Multipart Requests with requestParts() Source: https://context7.com/spring-projects/spring-restdocs/llms.txt Use `requestParts()` with `partWithName()` to document multipart request parts. `requestPartBody()` and `requestPartFields()` can document the body or fields of a specific part. ```java import static org.springframework.restdocs.request.RequestDocumentation.*; import static org.springframework.restdocs.payload.PayloadDocumentation.*; import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.multipart; @Test void multipartExample() throws Exception { this.mockMvc.perform(multipart("/upload").file("file", "example content".getBytes())) .andExpect(status().isOk()) .andDo(document("upload", requestParts( partWithName("file").description("The file to upload")))); // Writes: upload/request-parts.adoc // Also document the body/fields of a specific named part this.mockMvc.perform( multipart("/upload") .file("file", "content".getBytes()) .file("metadata", "{\"version\":\"1.0\"}".getBytes())) .andExpect(status().isOk()) .andDo(document("upload-with-metadata", requestParts( partWithName("file").description("The file to upload"), partWithName("metadata").description("Metadata as JSON")), requestPartFields("metadata", fieldWithPath("version").description("The version of the file")))); // Writes: upload-with-metadata/request-part-metadata-fields.adoc } ``` -------------------------------- ### Custom Snippet Format with MockMvc Source: https://github.com/spring-projects/spring-restdocs/blob/main/spring-restdocs-docs/src/docs/antora/modules/reference/pages/configuration/snippet-template-format.adoc Demonstrates how to configure a custom snippet template format for MockMvc tests. This is useful when you want to use a different documentation format than the default Asciidoctor. ```java given(this.spec).mockMvc(standaloneSetup(this.controller).build(), customFormat("markdown")) ``` -------------------------------- ### Document Request and Response Headers with MockMvc Source: https://github.com/spring-projects/spring-restdocs/blob/main/spring-restdocs-docs/src/docs/antora/modules/reference/pages/documenting-your-api/http-headers.adoc Use `requestHeaders` and `responseHeaders` to document HTTP headers for requests and responses respectively. The `headerWithName` method is used to specify individual headers. ```java import static org.springframework.restdocs.headers.HeaderDocumentation.headerWithName; import static org.springframework.restdocs.headers.HeaderDocumentation.requestHeaders; import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document; import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessResponse; import static org.springframework.restdocs.operation.preprocess.Preprocessors.prettyPrint; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders; import org.springframework.test.web.servlet.MockMvc; @WebMvcTest class HttpHeadersMockMvcTests { @Autowired private MockMvc mockMvc; @Test void httpHeaders() throws Exception { this.mockMvc .perform( RestDocumentationRequestBuilders.get("/hotels/1") .header("Authorization", "Basic user:password") ) .andDo( document( "request-headers", preprocessResponse(prettyPrint()), requestHeaders( headerWithName("Authorization").description("HTTP basic authentication header") ) ) ); } } ``` -------------------------------- ### Document Path Parameters with MockMvc Source: https://github.com/spring-projects/spring-restdocs/blob/main/spring-restdocs-docs/src/docs/antora/modules/reference/pages/documenting-your-api/path-parameters.adoc Use `pathParameters` and `parameterWithName` to document request path parameters for MockMvc tests. This ensures that all documented parameters are present in the request. ```java given().standaloneSetup(new RestDocumentationController()).mockMvc(standaloneSetup(new RestDocumentationController())) .when() .get("/latitude/37.422/longitude/-122.084") .then() .assertThat() .apply(document("path-parameters", pathParameters( parameterWithName("latitude").description("The latitude of the location"), parameterWithName("longitude").description("The longitude of the location")))) .statusCode(200); ``` -------------------------------- ### Documenting HAL Links with WebTestClient Source: https://github.com/spring-projects/spring-restdocs/blob/main/spring-restdocs-docs/src/docs/antora/modules/reference/pages/documenting-your-api/hypermedia.adoc Configure Spring REST Docs to produce a snippet describing HAL format links using WebTestClient. Uses the static `halLinks` method. ```java given(this.restDocumentation) .upon(halLinks()) .withHypermedia(linksTo(MyResource.class, "my-resource")) .and(linkWithRel("alpha").description("The alpha link")) .and(linkWithRel("bravo").description("The bravo link")) .when(this.webTestClient.get().uri("/my-resource").exchange()) .then(document("hypermedia/links")); ``` -------------------------------- ### Documenting Path Parameters (MockMvc) Source: https://context7.com/spring-projects/spring-restdocs/llms.txt Use pathParameters() with parameterWithName() to document URI template variables. Use RestDocumentationRequestBuilders.get() for path parameter extraction. The test fails for undocumented path parameters. Ensure RequestDocumentation and MockMvcRestDocumentation are imported. ```java import static org.springframework.restdocs.request.RequestDocumentation.*; import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document; import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.get; @Test void pathParametersExample() throws Exception { this.mockMvc.perform(get("/locations/{latitude}/{longitude}", 51.5072, 0.1275)) .andExpect(status().isOk()) .andDo(document("locations", pathParameters( parameterWithName("latitude").description("The location's latitude"), parameterWithName("longitude").description("The location's longitude")))); // Writes: locations/path-parameters.adoc } ``` -------------------------------- ### Configure WebTestClient with RestDocumentationConfigurer Source: https://github.com/spring-projects/spring-restdocs/blob/main/spring-restdocs-docs/src/docs/antora/modules/tutorial/pages/getting-started/index.adoc Configure the `WebTestClient` instance by adding `WebTestClientRestDocumentationConfigurer` as an `ExchangeFilterFunction`. Obtain the configurer from `WebTestClientRestDocumentation.documentationConfiguration()`. ```java include-code::webtestclient/ExampleApplicationTests[] ``` -------------------------------- ### Documenting Request Parts with MockMvc Source: https://github.com/spring-projects/spring-restdocs/blob/main/spring-restdocs-docs/src/docs/antora/modules/reference/pages/documenting-your-api/multipart.adoc Use `requestParts` to document the parts of a multipart request when using MockMvc. This ensures that only documented parts are used and all documented parts are present. ```java import static org.springframework.restdocs.request.RequestDocumentation.partWithName; import static org.springframework.restdocs.request.RequestDocumentation.requestParts; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.mock.web.MockMultipartFile; import org.springframework.test.web.servlet.MockMvc; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.multipart; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @WebMvcTest @AutoConfigureRestDocs class MultipartTest { @Autowired private MockMvc mockMvc; @Test void requestParts() throws Exception { MockMultipartFile file = new MockMultipartFile("file", "orig.txt", "text/plain", "content".getBytes()); this.mockMvc.perform(multipart("/upload").file(file)) .andExpect(status().isOk()) .andDo(document("request-parts", requestParts( partWithName("file").description("The file to upload") ))); } } ``` -------------------------------- ### Invoke Service and Document with WebTestClient Source: https://github.com/spring-projects/spring-restdocs/blob/main/spring-restdocs-docs/src/docs/antora/modules/tutorial/pages/getting-started/index.adoc Use WebTestClient to invoke a RESTful service and generate documentation snippets. This involves calling the service, asserting the response, and documenting the call using `WebTestClientRestDocumentation.document`. ```java include-code::webtestclient/InvokeService[] ``` -------------------------------- ### Documenting Root Array Payload Source: https://github.com/spring-projects/spring-restdocs/blob/main/spring-restdocs-docs/src/docs/antora/modules/reference/pages/documenting-your-api/request-response-payloads.adoc Demonstrates documenting a JSON payload where the root element is an array. Uses bracket notation for array elements and dot notation for fields within. ```json [ { "id":1 }, { "id":2 } ] ``` -------------------------------- ### Configure Custom Default Snippets with MockMvc Source: https://github.com/spring-projects/spring-restdocs/blob/main/spring-restdocs-docs/src/docs/antora/modules/reference/pages/configuration/default-snippets.adoc Use this snippet to configure custom default snippets when using MockMvc. ```java MockMvcRestDocumentation.documentationConfiguration(this.webApplicationContext) .snippets() .withDefaults(curlRequest()) ``` -------------------------------- ### Documenting Hypermedia Links Source: https://context7.com/spring-projects/spring-restdocs/llms.txt Use `links()` with `linkWithRel()` to document HATEOAS/hypermedia links in a response. This supports both Atom (array named `links`) and HAL (map named `_links`) formats automatically based on the content type. The test will fail if any documented links are absent. ```APIDOC ## GET / ### Description Documents hypermedia links in a JSON response, supporting HAL format. ### Method GET ### Endpoint / ### Parameters #### Response Links (HAL) - **self** (link) - Required - Self link - **users** (link) - Required - Link to the users resource ### Response #### Success Response (200) JSON response containing HAL links. ### Request Example ```java get("/").accept(MediaType.APPLICATION_JSON) ``` ## GET / ### Description Documents hypermedia links in a JSON response, specifying HAL format explicitly. ### Method GET ### Endpoint / ### Parameters #### Response Links (HAL) - **alpha** (link) - Required - Link to the alpha resource - **bravo** (link) - Required - Link to the bravo resource ### Response #### Success Response (200) JSON response containing HAL links. ### Request Example ```java get("/").accept(MediaType.APPLICATION_JSON) ``` ``` -------------------------------- ### Documenting Links with MockMvc Source: https://github.com/spring-projects/spring-restdocs/blob/main/spring-restdocs-docs/src/docs/antora/modules/reference/pages/documenting-your-api/hypermedia.adoc Configure Spring REST Docs to produce a snippet describing the response's links using MockMvc. Expects links with specific 'rel' attributes. ```java given(this.restDocumentation) .upon(hypermediaLinks()) .withHypermedia(linksTo(MyResource.class, "my-resource")) .and(linkWithRel("alpha").description("The alpha link")) .and(linkWithRel("bravo").description("The bravo link")) .when(this.mockMvc.perform(get("/my-resource"))) .then(document("hypermedia/links")); ``` -------------------------------- ### Apply Per-Test Preprocessors for Requests and Responses Source: https://context7.com/spring-projects/spring-restdocs/llms.txt Use `preprocessRequest` and `preprocessResponse` with built-in preprocessors like `modifyHeaders` and `prettyPrint` to customize individual test operations. Imports are required from `org.springframework.restdocs.mockmvc.MockMvcRestDocumentation` and `org.springframework.restdocs.operation.preprocess.Preprocessors`. ```java import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document; import static org.springframework.restdocs.operation.preprocess.Preprocessors.*; import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.get; // Per-test preprocessors: strip internal header, pretty-print JSON response @Test void preprocessingExample() throws Exception { this.mockMvc.perform(get("/")) .andExpect(status().isOk()) .andDo(document("index", preprocessRequest(modifyHeaders().remove("X-Internal-Token")), preprocessResponse(prettyPrint()))); } ``` -------------------------------- ### Maven Build Configuration for Spring REST Docs Source: https://context7.com/spring-projects/spring-restdocs/llms.txt Configure pom.xml to include spring-restdocs-mockmvc as a test dependency and set up the asciidoctor-maven-plugin with spring-restdocs-asciidoctor for snippet generation. ```xml org.springframework.restdocs spring-restdocs-mockmvc 4.0.1 test org.asciidoctor asciidoctor-maven-plugin 3.2.0 generate-docs prepare-package process-asciidoc html book org.springframework.restdocs spring-restdocs-asciidoctor 4.0.1 ``` -------------------------------- ### Reusing Field Descriptors for a Single Book (MockMvc) Source: https://github.com/spring-projects/spring-restdocs/blob/main/spring-restdocs-docs/src/docs/antora/modules/reference/pages/documenting-your-api/request-response-payloads.adoc Demonstrates reusing pre-defined field descriptors to document the 'title' and 'author' fields of a single book object when using MockMvc. ```java restDocumentation.document( requestFields( BookPayload.TITLE, BookPayload.AUTHOR ) ); ``` -------------------------------- ### Include All Snippets for an Operation Source: https://github.com/spring-projects/spring-restdocs/blob/main/spring-restdocs-docs/src/docs/antora/modules/reference/pages/working-with-asciidoctor.adoc Use the `operation` macro to import all snippets for a given operation. Ensure `spring-restdocs-asciidoctor` is included in your build configuration. ```asciidoc operation::index[] ``` -------------------------------- ### Document Path Parameters with WebTestClient Source: https://github.com/spring-projects/spring-restdocs/blob/main/spring-restdocs-docs/src/docs/antora/modules/reference/pages/documenting-your-api/path-parameters.adoc Use `pathParameters` and `parameterWithName` to document request path parameters for WebTestClient tests. This ensures that all documented parameters are present in the request. ```java webTestClient.get() .uri("/latitude/{latitude}/longitude/{longitude}", "37.422", "-122.084") .exchange() .expectStatus() .isOk() .apply(document("path-parameters", pathParameters( parameterWithName("latitude").description("The latitude of the location"), parameterWithName("longitude").description("The longitude of the location")))); ``` -------------------------------- ### Manually Include Snippets for an Operation Source: https://github.com/spring-projects/spring-restdocs/blob/main/spring-restdocs-docs/src/docs/antora/modules/reference/pages/working-with-asciidoctor.adoc This shows the manual inclusion of individual snippets for an operation, equivalent to using the `operation` macro with specific snippet selections. ```asciidoc [[example_curl_request]] = Curl request \include::{snippets}/index/curl-request.adoc[] [[example_http_request]] = HTTP request \include::{snippets}/index/http-request.adoc[] [[example_http_response]] = HTTP response \include::{snippets}/index/http-response.adoc[] ``` -------------------------------- ### Documenting Request Part Fields with MockMvc Source: https://github.com/spring-projects/spring-restdocs/blob/main/spring-restdocs-docs/src/docs/antora/modules/reference/pages/documenting-your-api/multipart.adoc Document the fields within a request part's payload using `requestPartFields` and `fieldWithPath` with MockMvc. This allows for detailed validation of structured part data. ```java import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath; import static org.springframework.restdocs.payload.PayloadDocumentation.requestPartFields; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.mock.web.MockMultipartFile; import org.springframework.test.web.servlet.MockMvc; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.multipart; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @WebMvcTest @AutoConfigureRestDocs class MultipartTest { @Autowired private MockMvc mockMvc; @Test void requestPartFields() throws Exception { MockMultipartFile metadata = new MockMultipartFile("metadata", "", "application/json", "{\"version\": \"1.0\"}".getBytes()); this.mockMvc.perform(multipart("/upload").file(metadata)) .andExpect(status().isOk()) .andDo(document("request-part-metadata-fields", requestPartFields("metadata", fieldWithPath("version").description("The version of the metadata") ))); } } ``` -------------------------------- ### Documenting Links with WebTestClient Source: https://github.com/spring-projects/spring-restdocs/blob/main/spring-restdocs-docs/src/docs/antora/modules/reference/pages/documenting-your-api/hypermedia.adoc Configure Spring REST Docs to produce a snippet describing the response's links using WebTestClient. Expects links with specific 'rel' attributes. ```java given(this.restDocumentation) .upon(hypermediaLinks()) .withHypermedia(linksTo(MyResource.class, "my-resource")) .and(linkWithRel("alpha").description("The alpha link")) .and(linkWithRel("bravo").description("The bravo link")) .when(this.webTestClient.get().uri("/my-resource").exchange()) .then(document("hypermedia/links")); ``` -------------------------------- ### Document Request and Response Headers with WebTestClient Source: https://github.com/spring-projects/spring-restdocs/blob/main/spring-restdocs-docs/src/docs/antora/modules/reference/pages/documenting-your-api/http-headers.adoc Use `requestHeaders` and `responseHeaders` to document HTTP headers for requests and responses when using WebTestClient. The `headerWithName` method is used to specify individual headers. ```java import static org.springframework.restdocs.headers.HeaderDocumentation.headerWithName; import static org.springframework.restdocs.headers.HeaderDocumentation.requestHeaders; import static org.springframework.restdocs.webtestclient.WebTestClientRestDocumentation.document; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest; import org.springframework.restdocs.webtestclient.WebTestClientBuilder; import org.springframework.test.web.reactive.server.WebTestClient; @WebFluxTest class HttpHeadersWebTestClientTests { @Autowired private WebTestClientBuilder webTestClientBuilder; @Test void httpHeaders() throws Exception { WebTestClient webTestClient = this.webTestClientBuilder.build(); webTestClient .get() .uri("/hotels/1") .header("Authorization", "Basic user:password") .exchange() .expectStatus() .isOk() .apply(document("request-headers", requestHeaders(headerWithName("Authorization").description("HTTP basic authentication header")))) .verify(); } } ``` -------------------------------- ### Documenting Fields of a Response Subsection with MockMvc Source: https://github.com/spring-projects/spring-restdocs/blob/main/spring-restdocs-docs/src/docs/antora/modules/reference/pages/documenting-your-api/request-response-payloads.adoc Produces a snippet describing the fields within a subsection of the response payload using MockMvc. It uses `beneathPath` to target the subsection and then documents specific fields. ```java mockMvc.perform(get("/documents/1")) .andExpect(status().isOk()) .andDo(document("fields-subsection", responseFields( beneathPath("weather.temperature").withSubsectionId("temp"), fieldWithPath("temp.high").description("The high temperature"), fieldWithPath("temp.low").description("The low temperature")))); ```