1

I have a small dilemma.

If you have the following URI endpoints:

/item
/item/{id}

If I make a GET request to /item I expect something like this:

<Items>
   <Item>...</Item>
   <Item>...</Item>
   ...
</Items>

If I make a GET request to /item/{id} I expect something like this:

<Item>
   ...
</Item>

Some of my fellow team members argue we should design the API so when someone does a GET for /item/{id} it should be returned as a collection of a single element. Like this:

<Items>
   <Item>...</Item>
</Items>

This seems wrong to me. Does it seem wrong to you too? Please explain why, so I might convince either myself to go with the always wrapped version of the resource or my fellow devs to go with the non-wrapped single resource.

c_maker
  • 19,076
  • 1
  • 24
  • 29

3 Answers3

5

Seems counterintuitive to me. You are potentially saving code effort on the client side by having one way of reading data from your two GET methods. This is of course countered by having extra code to wrap your single GET method in a collection.

If you want real world examples,

EDIT: Our API uses this HTTP status code structure

Community
  • 1
  • 1
Jason Watts
  • 3,800
  • 29
  • 33
5

Most importantly, there is no right and wrong answer to this question.

However, here is what I think.

If you want to return a single item, I would tend to do this:

GET /Item/{Id}

=>
<Item>
  ...
</Item>

If the {Id} does not exist then the server should return a 404.

If I want to return a collection of items, I would do

GET /Items
=>
<Items>
 <Item>...</Item>
 <Item>...</Item>
</Items>

If there are no items, then it should return a 200 with an empty <Items/> element.

If it really makes it easier for the client to deal with a collection that has just one element, then you could do something like this.

GET /Items?Id={Id}
=>
<Items>
  <Item> ... </Item>
</Items>

The difference here is that if the {Id} did not exist then I would tend to return 200 not a 404.

Darrel Miller
  • 139,164
  • 32
  • 194
  • 243
  • I think it is a great idea to provide the functionality with the /Items?Id={id} filter. The intent seems clear. – c_maker May 18 '11 at 01:14
0

I think your colleagues are right if you think about the consuming side of your REST service, which then can handle every response as a collection. And there's one more thing: If the {id} did not exist, what does your service return? Nothing? Then the consumer has to check for either a null result or error response, a single element or a collection. According to my experience getting a collection in any case (which may be empty) is the most convenient way to be served by a REST service.

ofi
  • 364
  • 1
  • 4