mustacheasciidocspring-restdocs

Adding extra information in Spring Rest-Docs using Attributes failing


I'm generating documentation for APIs that are written in Python. I am using Spring Rest-Docs for this which works flawless.

Now I must add a list of roles that are authorized to call the API to each API's documentation.

What I want to do, is list with every API which roles are valid, by injecting attributes, as per https://docs.spring.io/spring-restdocs/docs/current/reference/htmlsingle/#documenting-your-api-customizing-including-extra-information.

Like so:

@Test
public void get200_HelloWorld() throws Exception {
    this.testClient.get().uri("/hello_worlds")
        .exchange().expectStatus().isOk()
        .expectBody().consumeWith(document("{method-name}",
            requestHeaders(
                attributes(key("roles").value(
                    attributes(key("role").value("Smart User"),
                               key("role").value("Admin")))),
                    headerWithName("Accept").description("Response formats."))));
}

The snippet template I defined looks like:

Roles:
{{#roles}}
{{role}}
{{/roles}}

The code works and the test passes, but the documentation that is generated is not what I expected. The first key("role").value("Smart User") I add doesn't show. See:

Roles:
Admin

There's an error org.springframework.restdocs.mustache.MustacheException$Context: No method or field with name 'role' on line 2 reported as well.

How can I add multiple attributes and then also print them?

I am adding the attributes to the requestHeader documentation, because that is what I will have with every API call I document.

Thanks in advance,


Solution

  • Each attribute must have a unique key. You have two attributes with the key role. As a result, the second role attribute replaces the first.

    You could use a list instead:

    attributes(key("roles").value(Arrays.asList("Smart User", "Admin")))
    

    And then render each item in the list using {{.}}:

    Roles:
    {{#roles}}
    {{.}}
    {{/roles}}