Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return generated ID in RESTful POST?

Tags:

rest

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.

like image 648
Marcus Leon Avatar asked Oct 26 '09 14:10

Marcus Leon


People also ask

Should REST API return ID?

It doesn't matter if the resource returns an ID field. It is up to the client to keep a map of where it was obtained from. In a + b, the server would create a new resource.

Can a post request return a body?

Yes, even though it returns void, in a class which extends Resource, you have full access to the Response object object via the getResponse() method. So you can call getResponse().

What REST API should return?

The API should always return sensible HTTP status codes. API errors typically break down into 2 types: 400 series status codes for client issues & 500 series status codes for server issues. At a minimum, the API should standardize that all 400 series errors come with consumable JSON error representation.


1 Answers

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

like image 106
Darrel Miller Avatar answered Sep 21 '22 22:09

Darrel Miller