How to document top-level array as response payload with Spring REST Docs How to document top-level array as response payload with Spring REST Docs spring spring

How to document top-level array as response payload with Spring REST Docs


this is totally possible with 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. 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:

result.andDo(docHandler.document(    responseFields(subsectionWithPath("[]").description("A list of objects"))));