Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am using Spring REST Docs to document a REST API. I'm trying to document the following API operations:

GET /subsystems
GET /subsystems/some_name

For example, a call to GET /subsystems/samba returns the following JSON object:

{ 
  "id": "samba", 
  "description": "..." 
}

You could use the following snippet which uses Spring REST Docs to document this API operation:

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:

[ 
  { 
    "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. How should I do it?

like image 205
aaguilera Avatar asked Jul 01 '15 13:07

aaguilera


2 Answers

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.

like image 149
Michael Simons Avatar answered Nov 02 '22 03:11

Michael Simons


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")
)));
like image 2
Cepr0 Avatar answered Nov 02 '22 04:11

Cepr0