首页 > 解决方案 > 如何使用 spring restdocs 记录包含 JSON 对象的请求正文

问题描述

我正在使用 spring boot 2 来实现 REST API 服务,并想用 restdocs 记录它。

端点

POST /api/tags

带有请求正文

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

用于添加创建新标签。我查看了 restdocs 文档,但仍然找不到记录请求正文的 JSON 字段的方法,谁能帮我填写缺失的部分“......”。

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", ...... )));

标签: spring-bootspring-restdocs

解决方案


您需要用户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("....")
                                )
                        )
                );

这记录在官方文档中:https ://docs.spring.io/spring-restdocs/docs/current/reference/html5/#documenting-your-api-request-response-payloads


推荐阅读