apethedev
apethedev

Reputation: 36

How to use spring restdocs to document request body that contains a JSON object

I'm using spring boot 2 to implement REST API service and would like to document it with restdocs.

The endpoint

POST /api/tags

with request body

{"name":"Some Tag", "description":"This is Some Tag"}

is used to add create a new Tag. I've looked through the restdocs documentation, but still can't find a way to document the request body's JSON fields, Can anyone help me to fill the missing part "......".

TagRequest request = new TagRequest();
request.setName("Some Tag");
request.setDescription("This is Some Tag");
client.post().uri("/api/tags").body(BodyInserters.fromObject(request)).exchange()
        .expectStatus().isOk().expectBody(Integer.class)
        .consumeWith(document("add-tag", ...... )));

Upvotes: 2

Views: 3863

Answers (1)

Teocali
Teocali

Reputation: 2704

You need to user requestFields

client
                .post().uri("/api/tags")
                .body(BodyInserters.fromObject(request))
                .exchange()
                .expectStatus().isOk()
                .expectBody(Integer.class)
                .consumeWith(
                        document("add-tag",
                                requestFields(
                                        fieldWithPath("name").description("...."),
                                        fieldWithPath("name").description("....")
                                )
                        )
                );

This is documented in official doc : https://docs.spring.io/spring-restdocs/docs/current/reference/html5/#documenting-your-api-request-response-payloads

Upvotes: 9

Related Questions