Search code examples
restangularjsangularjs-resource

'Best' practice for restful POST response


So nothing new here I am just trying to get some clarification and cannot seem to find any in other posts.

I am creating a new resource restulfully, say:

/books (POST)

with a body:

{
  title: 'The Lion, the Witch and the Wardrobe',
  author: 'C. S. Lewis'
}

I know that I should return a 201 (Created) with a Location header of the new resource:

Location: /books/12345

The question I cannot seem to answer for myself is what should the server return in the body.

I have often done this type of response:

{
  id: 12345,
  title: 'The Lion, the Witch and the Wardrobe',
  author: 'C. S. Lewis'
}

I have done this for a couple reasons:

  1. I have written api for front end frameworks like angularjs. In my particular case I am using angular resources and I often need just the id for the resource to locate it. If I did not return the id in the response body I would need to parse it out of the Location header.
  2. In a GET of all books I usually return the entire object not just the id. In this sense my client code does not have to differentiate where to get the id from (location header or body).

Now I know I am really in the grey area here, but most people are saying that returning the entire resource is 'bad' practice. But what if the server changes/adds information to the resource. It definitely adds the id, but might also add other things like a timestamp. In the case that I do not return the entire resource, is it really better to do a POST, return the id, then have the client perform a GET to get the new resource.


Solution

  • Returning the whole object on an update would not seem very relevant, but I can hardly see why returning the whole object when it is created would be a bad practice in a normal use case. This would be useful at least to get the ID easily and to get the timestamps when relevant. This is actually the default behavior got when scaffolding with Rails.

    I really do not see any advantage to returning only the ID and doing a GET request after, to get the data you could have got with your initial POST.

    Anyway as long as your API is consistent I think that you should choose the pattern that fits your needs the best. There is not any correct way of how to build a REST API, imo.