Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
685 views
in Technique[技术] by (71.8m points)

rest - '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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Returning the new object fits with the REST principle of "Uniform Interface - Manipulation of resources through representations." The complete object is the representation of the new state of the object that was created.

There is a really excellent reference for API design, here: Best Practices for Designing a Pragmatic RESTful API

It includes an answer to your question here: Updates & creation should return a resource representation

It says:

To prevent an API consumer from having to hit the API again for an updated representation, have the API return the updated (or created) representation as part of the response.

Seems nicely pragmatic to me and it fits in with that REST principle I mentioned above.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...