rawData rawData - 1 year ago 118
reST (reStructuredText) Question

rest api response format

Should I treat all api response as "resource" and return a JSON object or simple array would be appropriate as well ?

for instance are all of the below responses valid?

GET /rest/someresource
should return collection of ids

  1. [{id:1},{id:2}]

  2. {{id:1},{id:2}}

  3. [1,2]

GET /rest/someresource?id>0
search for ids bigger than zero and return collection of ids

  1. [{id:1},{id:2}]

  2. {{id:1},{id:2}}

  3. [1,2]

Answer Source

Collection Resources

It is acceptable to return an array of resources - either a list of ids, or object structures - such a thing is commonly known as a 'collection' resource.

See http://51elliot.blogspot.com.au/2014/06/rest-api-best-practices-4-collections.html for an examination of resources and collections.

While not required by REST, it's common to use a plural noun to refer to a collection resource - e.g.


REST also requires the use of defined media types, and there are a couple available to assist with collections, e.g.:

  • Collection+json
    • Provides a structure with meta data around a list of items wherein you define the structure of each item as your resource
  • HAL
    • provides a structure with embedded collections and embedded resources

And many more

All provide a defined structure for including hypermedia links for your resource, or each resource in your collection - and if you are doing REST this is one of the things that the spec says you MUST do (even though many people don't).

Your Proposed Json Structures

Some more specific comments on your proposed json structures:

Option 2 is not valid json. Consider:


A json object must have a name:value pair, e.g.


would be valid - but not very useful!

Also - strictly for json, the name should be enclosed in quotes. the value may be enclosed in quotes if it is a string.

So if you don't want to use a commonly used media type as referenced above, your options are 1 or 3. which should be:

  • [{"id":1},{"id":2}]
  • [1, 2]

Both are valid, however option 1 will give you more flexibility to add more properties to each element of the array if you decide in the future you would like to return more than an id. e.g. at some point in the future you might decide to return:


Option 3 will only ever be able to return a list of ids.

So personally I would go with option 1.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download