The top level representation returned by any resource request should always be the resource itself. For example, the call
GET /v1/products/76124
should return a response similar to
{ "status":"OK", "recordCount":1, "startTimestamp":"2013-12-02T19:31:35.5362308Z", "endTimestamp":"2013-12-02T19:31:35.6299946Z", "timeTaken":0.0937638, "data":[{ "products" :[{ "product_id": "76124", "name": "The Amazing Widget", "weight": "7.2 oz", ... }] }] }
In this example, the response data is embedded within an envelope containing other related data specific to the request, including any status codes, timestamps, etc. This information is not required and may be eliminated in favor of simply returning the “data” hash at the top level.
Note that the “products” value – which should contain the information specific to the Product resource, as indicated in the endpoint – is actually a one-item array containing a hash rather than a hash itself. This allows the API to use the same structure whether it’s returning a single requested object or whether returning a list of objects. Returning a consistent format like this makes it easier for the client developer to create a single handler for the response. For example,
GET /v1/products
should return a list of products in the same format:
{ "status":"OK", "recordCount":3, "startTimestamp":"2013-12-02T19:31:35.5362308Z", "endTimestamp":"2013-12-02T19:31:35.6299946Z", "timeTaken":0.0937638, "data":[{ "products" :[ { "product_id": "76124", "name": "The Amazing Widget", "weight": "7.2 oz", ... }, { "product_id": "84567", "name": "Rubber Ducky", "weight": "4.6 oz", ... }, { "product_id": "76124", "name": "Whoopie Cushion", "weight": "2.2 oz", ... }, ] }] }
This same response format should be returned whether the resource is called directly, i.e.
GET /v1/products/76124
Or whether it’s called through a relationship, i.e.
GET /v1/categories/39/products/76124
hey Rob – I believe the recordCount property for the 2nd JSON example (the collection route) should be > 1?
Good catch – thank you for this. Fixed!
Whatup with the status’s in the response? HTTP Response codes should be used heavily.
This is in addition to HTTP Response codes. There are some business cases where embedding the response in an envelope – such as is done in this example – is beneficial. Some folks include either a copy of the status here or a more detailed status aside from just “OK”. I left that in place here to demonstrate that, but realize it has created more confusion than anything else. I’ll likely remove it soon, just to keep it cleaner.
Thanks for pointing this out, though. Great question!