Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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?

share|improve this question
    
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 '12 at 4:33

1 Answer 1

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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