17

I'm building a REST API which allows inserts (POST, not idempotent) and updates (PUT, idempotent) requests to add/update database to our application.

I'm wondering if there are any standards or best practices regarding what data we send back to the client in the response for a POST (insert) operation. We need to send back at least a record ID value (e.g. your new record is record #1234).

Should we respond with the full object? (e.g. essentially the same response they'd get back from a "GET /object_type/1234" request)

Should we respond with only the new ID value? (e.g. "{ id: 1234 }", which means that if they want to fetch the whole record they need to do an additional HTTP GET request to grab the full record)

A redirect header pointing them to the URL for the full object?

Something else entirely?

1
  • I'm oot sure about best practice but for me personally I would probably consider just returning the newly created id if successfull otherwise -1 etc Be interested to see what others say though
    – dreza
    Oct 24, 2012 at 4:33

1 Answer 1

15

Well, in a REST interface, following HTTP where ever possible, I would return a 201 and an URI in the Location header field to the newly created Resource. Here is what Status Code Definitions says:

10.2.2 201 Created

The request has been fulfilled and resulted in a new resource being created. The newly created resource can be referenced by the URI(s) returned in the entity of the response, with the most specific URI for the resource given by a Location header field. The response SHOULD include an entity containing a list of resource characteristics and location(s) from which the user or user agent can choose the one most appropriate. The entity format is specified by the media type given in the Content-Type header field. The origin server MUST create the resource before returning the 201 status code. If the action cannot be carried out immediately, the server SHOULD respond with 202 (Accepted) response instead.

If something went wrong, I would argue you shouldn't return -1 as others have said, but simply a Client or Server Error Code (4xx or 5xx). For example, if a user is not allowed to create some new resource, you would simply return a "401 Unauthorized", nothing more and nothing less.

2
  • What about the body? empty or the entire newly created object in response?
    – Developer
    May 24, 2019 at 11:30
  • Two common options I know of are 1) setting the location header to where the new entity can be found, or, 2) including the new entity in the body. I personally go with the latter for practical reasons. Somtimes combined for a more resty feeling ;) May 24, 2019 at 13:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.