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.
Objectives
- Return hierarchical data structure in REST response
- Create valid REST request which allows to define what data hierarchical structure is expected
Solution
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:
{"object1":[ {"id":1, "name":"name1", "object2":[ {"id":"2", "name":"name2"} ], "object3":[ {"id":"3", "name":"name3", "object4":[ {"id":"4", "name":"name4"} ] } ] } ] }
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:
queryTree=[“object2”,{“object3”:[“object4”]}]
[ "object2", { "object3":[ "object4" ] } ]
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.