TechBuzzPro

Spring REST Docs Form Parameters: Documenting Request Fields in Tests

· 5 min read · Apps & Browsers

In this article
  1. Formula
  2. Worked Example
  3. How Spring REST Docs Handles Form Parameters
  4. Why This Matters for API Documentation
  5. Common Pitfalls and How to Avoid Them
  6. Alternatives for Documenting Form Parameters
  7. Frequently Asked Questions

Yes, Spring REST Docs can document form parameters as request fields in tests, and it does so through the requestFields() method combined with a formParameters() helper. This approach lets you generate accurate API documentation directly from your MockMvc or WebTestClient tests, ensuring the docs always match the actual behavior.

in t | Finish time | min | 50 | 0
in d | Distance | km | 10 | 0
out pace | Average pace | min/km | t / d | 2
out speed | Average speed | km/h | d / (t / 60) | 2

Formula

The average pace (in minutes per kilometer) is calculated by dividing the total time by the distance:

pace = t / d

Where:

  • t = finish time in minutes
  • d = distance in kilometers

The average speed (in km/h) is the distance divided by the time in hours:

speed = d / (t / 60)

Both results are rounded to two decimal places.

Worked Example

Using the default values from the calculator (finish time = 50 minutes, distance = 10 km):

  1. Pace = 50 / 10 = 5.00 min/km
  2. Speed = 10 / (50 / 60) = 10 / 0.8333 = 12.00 km/h

The calculator shows 5.00 min/km and 12.00 km/h, matching these results.

How Spring REST Docs Handles Form Parameters

Spring REST Docs is a testing library that generates documentation snippets from the requests and responses your tests make. For form parameters, the library treats them as request fields, so you use the same requestFields() API that you would for a JSON payload, but you must also tell the framework that the fields come from a form submission.

The key is the formParameters() method from the org.springframework.restdocs.request package. In a MockMvc test, you write:

mockMvc.perform(post("/api/submit")
    .contentType(MediaType.APPLICATION_FORM_URLENCODED)
    .param("name", "John")
    .param("age", "30"))
    .andExpect(status().isOk())
    .andDo(document("submit-form",
        requestFields(
            fieldWithPath("name").description("The user's name"),
            fieldWithPath("age").description("The user's age")
        )));

Notice that you do not call formParameters() directly in the snippet; instead, you use requestFields() and the library automatically detects that the request is form-encoded. However, if you want to be explicit, you can use formParameters() as an alias. In either case, the generated Asciidoc or Markdown snippet will list the fields under a "Request Fields" section.

Why This Matters for API Documentation

Form-encoded requests are common in traditional web applications and OAuth2 token endpoints. Without proper documentation, clients cannot know which parameters are required, their types, or their meanings. Spring REST Docs solves this by tying documentation to the actual test execution, so if a parameter is removed or renamed, the documentation fails to build until the test is updated. This keeps the docs in sync with the code, a major advantage over hand-written documentation that often drifts.

For example, an OAuth2 token endpoint might accept grant_type, username, and password. Using Spring REST Docs, you can document these as request fields, and the generated snippet will appear in your API reference guide with the descriptions you provide.

Common Pitfalls and How to Avoid Them

  • Missing content type: If you forget to set contentType(MediaType.APPLICATION_FORM_URLENCODED), Spring REST Docs may treat the parameters as query parameters, and the documentation will be incorrect or the test may fail.
  • Using the wrong method: Some developers try to use queryParameters() for form data. That method is for query string parameters (e.g., ?page=2), not for form bodies. Always use requestFields() for form parameters.
  • Not documenting optional fields: By default, all fields are considered required. If a field is optional, you must mark it with .optional() in the field descriptor, otherwise the documentation will incorrectly state it is mandatory.
  • Forgetting to use the correct test client: For WebTestClient (reactive), the API is slightly different: you use form() to set the body, but the documentation call remains the same. Ensure you import the correct static methods.

Alternatives for Documenting Form Parameters

Spring REST Docs is not the only way to document form parameters. Alternatives include:

  • OpenAPI (Swagger) annotations: You can annotate your controller methods with @Parameter or use @RequestBody with a DTO that has form-specific annotations. Tools like springdoc generate documentation from these annotations.
  • Hand-written documentation: You can write the docs manually, but this risks becoming outdated.
  • Postman/Insomnia: These tools can generate documentation from your requests, but they are not integrated into the build process.

Spring REST Docs stands out because it produces documentation that is verifiably accurate at build time, which is especially valuable in regulated environments or when you have a strict API contract.

Frequently Asked Questions

Can I use formParameters() with WebTestClient?

Yes, the same requestFields() method works with WebTestClient. You set the form body using .body(BodyInserters.fromFormData(...)) and then document it with the same field descriptors. The library handles the encoding difference transparently.

How do I document a file upload as a form parameter?

For multipart file uploads, use requestParts() instead of requestFields(). File uploads are not considered simple form parameters; they are parts. You can document each part with partWithName() and provide a description.

What happens if I don't document a form parameter?

If you do not include a field descriptor for a parameter that is actually sent, the test will fail during documentation generation. This is intentional: it forces you to keep the documentation complete and up to date.

Can I document form parameters in a reactive (WebFlux) application?

Yes, Spring REST Docs supports WebTestClient for reactive applications. The process is identical; you just use the WebTestClient equivalent of the MockMvc methods. The documentation snippets are the same format.

Is there a way to generate the field descriptions automatically?

No, Spring REST Docs requires you to write the descriptions manually. This is by design, as it forces you to think about the meaning of each field. However, you can use constants or enums to avoid repetition across multiple tests.

Does Spring REST Docs support form parameters in Kotlin?

Yes, it works with Kotlin as well. The API is the same, and you can use Kotlin DSLs if you prefer. The documentation generation is independent of the language used in the test.