How to return generated ID in RESTful POST?

2019-03-17 07:19发布

问题:

Let's say we have a service to add a new hotel:

> POST /hotel
> <hotel>
>   <a>aaa</a>
>   <b>aaa</b>
>   <c>aaa.......this is 300K</c>
> </hotel>

And then we have a get:

> GET /hotel

< HTTP/1.1 200 OK
< <hotel>
<   <a>aaa</a>
<   <b>aaa</b>
>   <c>aaa.......this is 300K</c>
< </hotel>

Question is what do we return for the initial POST creation? We would like to return the ID (generated on the server) for a "reference" to the new resource but we don't want to return all the hotel data as in our case one of the data fields is a flat file of ~300K.

So should you just return:

< HTTP/1.1 200 OK
< <hotel>
<   <id>123</id>
< </hotel>

Or should you return the full object:

< HTTP/1.1 200 OK
< <hotel>
<   <id>123</id>
<   <a>aaa</a>
<   <b>aaa</b>
>   <c>aaa.......this is 300K</c>
< </hotel>

??

I'm interested in the restful best practice.

Note: this related post talks more about what to return but less about how to return it.

回答1:

Return the status code 201 - Created, and put the URL in the Location header. You don't need to return a body at all.



回答2:

REST is all about URL's to resources.

The best RESTful practice is to return the URL used to access the resource just created.

I would not return the whole document. Unless it is important to the protocol for some reason (like the server might change the data that the client submits and the client wants to confirm that it is ok). If it is not important, the client already knows the data.

If you return just the ID, the client won't know what to do with it. But returning a URL will allow the client to continue the REST interaction with the server (presumably by getting a service description document). This is not to say that you can't return the ID along with the URL. But the URL, because it is a web system, is the most important piece of information you can know. Additionally, the ID is likely to be something you need internally for your backend, not something the client should ever have to worry about.

EDIT:
As to whether you should wrap the returned URL in XML, it really depends on your protocol. If you think you might want to return other data in the future, XML would be more prudent. Having a named file format would let you version your services better (by changing the document type header). But you could just return the URL.



回答3:

The one advantage of returning a Location header and the actual entity body on the response is that the client can receive the resulting representation in a single round-trip to the server. AtomPub does this, for example.



标签: rest