Spring REST Docs

repository·main·Indexed 22 days ago

https://github.com/spring-projects/spring-restdocs

A documentation tool that generates human-readable API guides by combining manual Asciidoctor content with automated test examples from Spring MVC tests. It supports generating CLI request snippets for curl and HTTPie, customizable Mustache templates for snippet output, and parameterized output directories for organizing documentation snippets by test class or method name.

Tokens
18.9K
Snippets
53
Records
84
Agent score
78%

What's inside Spring REST Docs

  1. Overview of Spring REST Docs

    main

    Spring REST Docs is a tool for documenting RESTful services by combining hand-written documentation with auto-generated snippets. It uses a test-driven approach to ensure documentation accuracy: snippets are produced during the execution of tests, and if a snippet becomes incorrect due to changes in the service, the corresponding test will fail.

    Key features include:

    • Accuracy: Documentation is tied to functional tests.
    • Abstraction: It focuses on documenting the API (HTTP requests and responses) rather than the internal implementation details, allowing the service to evolve without requiring documentation rework.
    • Flexible Output: Uses Asciidoctor by default to produce HTML, but can be configured to use Markdown.
  2. Understand Markdown limitations in Spring REST Docs

    main

    When using Markdown for Spring REST Docs documentation, be aware of two primary limitations compared to Asciidoctor:

    1. Tables: Standard Markdown lacks official support for tables. Spring REST Docs' default Markdown snippet templates utilize the Markdown Extra table format. If you are writing custom documentation, ensure your Markdown processor supports this specific extension.
    2. Snippet Inclusion: Markdown does not have built-in support for including one file within another (e.g., including generated test snippets into a main documentation file). To include generated snippets, you must use an external tool or a Markdown processor that supports file inclusion functionality.
  3. How Spring REST Docs determines content encoding

    main

    When Spring REST Docs converts request or response content to a String, it follows this priority for determining the charset:

    1. Content-Type Header: It uses the charset parameter specified in the Content-Type header if available.
    2. JVM Default: If no charset is specified in the header, it falls back to the JVM's default Charset.

    You can influence the fallback behavior by setting the file.encoding system property of the JVM.

  4. How to write a custom Preprocessor

    main

    If the built-in preprocessors do not meet your requirements, you can extend the functionality in two ways:

    1. Full Preprocessor: Implement the OperationPreprocessor interface to gain full control over the operation. You can use it exactly like the built-in preprocessors.
    2. Content-only Modifier: If you only need to modify the body (content) of a request or response, implement the ContentModifier interface and use it with the built-in ContentModifyingOperationPreprocessor. This is often simpler than implementing a full OperationPreprocessor.
  5. Customize how constraints are found

    main

    By default, Spring REST Docs uses a Bean Validation Validator to find property constraints.

    If you need to change this behavior:

    • Custom Validator: Create ConstraintDescriptions using a custom ValidatorConstraintResolver to provide a different Validator.
    • Full Control: Implement your own ConstraintResolver and pass it to the ConstraintDescriptions constructor to take complete control over how constraints are resolved.
  6. Configure hypermedia link formats (Atom and HAL)

    main

    Spring REST Docs automatically detects the link format based on the response Content-Type:

    • Atom: Links are expected in an array named links. This is the default for application/json compatible types.
    • HAL: Links are expected in a map named _links. This is the default for application/hal+json compatible types.

    If you are using Atom or HAL formats with a non-standard Content-Type, you must explicitly provide a LinkExtractor to the links() method.

  7. Understand null safety in Spring REST Docs

    main

    Spring REST Docs uses JSpecify annotations to explicitly declare the nullability of its API. The purpose of these annotations is to prevent NullPointerException at runtime by enabling build-time nullability checks.

    Depending on your language, you can leverage these annotations as follows:

    • Kotlin: Null safety is handled automatically. Kotlin translates JSpecify annotations into its own native null safety system.
    • Java: Null safety requires external tooling to perform build-time checks. You can use an IDE that supports JSpecify (such as IntelliJ IDEA) or a static analysis tool like NullAway.
  8. Use relaxed path parameter documentation

    main

    By default, Spring REST Docs enforces strict path parameter documentation: the test fails if an undocumented parameter is used, or if a documented parameter is missing from the request (unless marked as optional).

    If you want to document only a subset of path parameters without causing test failures for the missing ones, use the relaxedPathParameters method from org.springframework.restdocs.request.RequestDocumentation instead of pathParameters.

  9. Include extra information in snippets using attributes

    main

    You can pass custom data into snippet templates using attributes. This data is made available during the Mustache rendering process.

    There are two ways to provide these attributes:

    1. On a descriptor: Use the .attributes() method on a specific descriptor (e.g., a field descriptor) to add attributes to that specific element.
    2. On the snippet level: Pass attributes as arguments when calling snippet methods like curlRequest(), httpRequest(), httpResponse(), etc. These attributes apply to the entire snippet.

    Example Workflow:

    1. Add attributes in your test code (e.g., constraints for a field or title for a snippet).
    2. Update your custom .snippet template to reference these attributes using Mustache syntax (e.g., {{title}} or {{constraints}}).
  10. Use JSON field paths for documentation

    main

    When documenting JSON payloads, you can identify fields using dot notation or bracket notation:

    • Dot notation: Uses . to separate keys (e.g., a.b). It is concise but cannot handle keys containing dots.
    • Bracket notation: Wraps keys in square brackets and single quotes (e.g., ['a']['b']). This allows keys to contain dots (e.g., ['a.b']).
    • Arrays: Use [] to identify an array. For example, a.b[] refers to the elements within array b of object a.
    • Root Arrays: Use [] to refer to the entire array if the payload is a root-level array.
    • Wildcards: Use * to match fields with different names (e.g., users.*.role).
  11. How form parameter documentation works

    main

    When you use formParameters or relaxedFormParameters, Spring REST Docs generates a snippet named form-parameters.adoc containing a table of the supported form parameters.

    Strict Mode (Default)

    By default, formParameters operates in a strict mode:

    1. Undocumented parameters: If the request contains a parameter not defined in your documentation, the test fails.
    2. Missing parameters: If a documented parameter is missing from the request, the test fails (unless the parameter is marked as optional).

    Relaxed Mode

    Using relaxedFormParameters allows the request to contain undocumented parameters without triggering a test failure. This is ideal when you only want to document a specific subset of the available form data.