We are creating a REST API and we currently have two approaches for defining the resources.
Basically we have Patients
, Studies
and Images
where a Patient
has n Studies
and a Study
has n Images
.
Hierarchical Approach
/webapi/patients/0/studies/12/images
The hierarchy is visible in the URI
To search for all images we would need a search resource
/webapi/search?q=imageName:mountain
Flat Approach
/webapi/patients/0
/webapi/studies/12
/webapi/images/
The hierarchy is done by an attribute (for example study 12
has a patientId
of 0).
To search for all images we can search on the resource itself:
/webapi/images?q=imageName:mountain
Is there a best practice approach or does anyone have experienced a similar scenario? Is a search resource REST or is it bad that the relation from an image is not visible in the flat approach.
Also we need to think about move and modification.
Flat and hierarchical URIs could be both RESTful. The problem is elsewhere. Being RESTful suppose that URIs are identifiers of resources.
What resource is identified by /wepapi/patients/0/studies/12/images
? The images of studies 12.
Is it really a bad identifier? Not really.
Could it be better? Definitely:
wepapi
(the way you get a representation of the resource) has nothing to do with the abstract resource. The most RESTful approach would be to have the same URI for different concrete "representations" of the same abstract resource (see HTTP Accept
headers for more information).patients/0
is not needed to identify those images. You might think that it would be cool for client software to get this datum by parsing the URI, but... they are not supposed to do that. URI are said to be "opaque".What resource is identified by /search?q=imageName:mountain
? The images that are named "mountain".
Is it really a bad identifier? Not really. Could it be better? Definitely:
search
looks like a verb, which should raise a lot of warnings in a RESTful designer mind. In a way, we could say that the URI identify "a search" or "search results" (a noun and not a verb), but it is safer to consider that it identifies "images".Last but not least, choosing between /studies/12/images
and /images/?studies=12
in order to be "coherent" with either /studies/12
or /images/?name=mountain
is purely a software design choice. Take the solution that will be the more elegant for your application. It has nothing to do with REST, since URIs are not supposed to be hacked (remember, they are supposed to be "opaque"). The links between URIs are in their representations (JSON, XML, HTML...), not in their structure.