REST with hierarchical (tree) data query and response payload

Probably everyone using REST webservices face requirements which makes you deal with hierarchical (tree) data structures. How to clearly define when data is expected to be returned in a hierarchical structure and when just a flat object? And what if you need different hierarchical responses in different use cases for the same REST resource? Here I’m going to tell you what approach I came up when faced such requirements.


  • Return hierarchical data structure in REST response
  • Create valid REST request which allows to define what data hierarchical structure is expected


Data hierarchy in response payload can be formatted in classic array of multilevel arrays. Lets consider as an example this little pseudo object hierarchy:

Sample json representation could look like this:


To have hierarchy requests enabled, we need to have a special parameter which we pass to resource via URL. Lets name this parameter queryTree. Objects hierarchies in projects can grow to really hight complexity. Thus it is important to have a clear format for queryTree. I’d propose to use json. Everyone dealing with REST api’s is familiar with it. In this json we are going to operate only with object names, as we just need to tell backend which objects we’re expecting to get in response. So if we want to get json sample exposed above, we would need to define it in queryTree parameter like this:



Consider, that we miss object1 in tree definition. Thats because object1 is the root object which is pointed by REST URI. If completely skip queryTree parameter, means do not request hierarchy, only flat object1 would be returned in response. Complete REST request could look like this:

GET //localhost/dataService/object1&queryTree=[“object2”,{“object3”:[“object4”]}]

In the backend implementation, such kind of hierarchies could be gathered by iterative methods, which grow up structure by reading queryTree parameter:

This is it. Its my approach how I deal with hierarchies in REST webservices.