[英]How to document top-level array as response payload with Spring REST Docs
I am using Spring REST Docs to document a REST API. 我正在使用Spring REST Docs记录REST API。 I'm trying to document the following API operations:
我正在尝试记录以下API操作:
GET /subsystems
GET /subsystems/some_name
For example, a call to GET /subsystems/samba
returns the following JSON object: 例如,对
GET /subsystems/samba
的调用将返回以下JSON对象:
{
"id": "samba",
"description": "..."
}
You could use the following snippet which uses Spring REST Docs to document this API operation: 您可以使用以下片段,这些片段使用Spring REST Docs记录此API操作:
this.mockMvc.perform(
get("/subsystems/samba").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk()).andDo(
document("subsystem").withResponseFields(
fieldWithPath("id").description("Subsystem name"),
fieldWithPath("description").description("Subsystem description")));
My problem is with the first operation: the call to GET /subsystems
returns a JSON array: 我的问题是第一次操作:对
GET /subsystems
的调用返回一个JSON数组:
[
{
"id" : "samba",
"description" : "..."
},
{ "id" : "ownCloud",
"description" : "..."
},
{ "id" : "ldap",
"description" : "..."
}
]
I could not find any example showing how to document this kind of result in the Spring REST Docs documentation. 我在Spring REST Docs文档中找不到任何示例来说明如何记录这种结果。 How should I do it?
我该怎么办?
this is totally possible with Spring Rest Doc 1.0 Spring Rest Doc 1.0完全有可能
this.mockMvc.perform(
get("/subsystems").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk()).andDo(
document("subsystem").withResponseFields(
fieldWithPath("[].id").description("Subsystem name"),
fieldWithPath("[].description").description("Subsystem description")));
To document the array itself, use 要记录数组本身,请使用
this.mockMvc.perform(
get("/subsystems").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk()).andDo(
document("subsystem").withResponseFields(
fieldWithPath("[]").description("An array of subsystems"),
fieldWithPath("[].id").ignore(),
fieldWithPath("[].description").ignore()));
I have ignored the other two fields if you just want to document the array itself. 如果您只想记录数组本身,我将忽略其他两个字段。 You can combine both solutions as well.
您也可以结合使用这两种解决方案。
Enjoy. 请享用。
Edit: I learned from Andy Wilkinson that if you document the top level array, all fields are marked as documented. 编辑:我从安迪·威尔金森(Andy Wilkinson)了解到,如果您记录了顶层数组,则所有字段都将标记为已记录。 So if you want to document just the array, you can safely skip the ignores.
因此,如果您只想记录数组,则可以安全地跳过忽略。
subsectionWithPath
method of PayloadDocumentation
works with []
as well, without necessary to ignore the rest of fields: PayloadDocumentation
subsectionWithPath
方法PayloadDocumentation
可以与[]
一起使用,而不必忽略其余字段:
result.andDo(docHandler.document(
responseFields(subsectionWithPath("[]").description("A list of objects")
)));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.