Search code examples
resthttpput

REST PUT create or update


I want to create or update an item in one go with the following request:

PUT /items/{id}

Should I return 201 Created if the item has been created and 204 No Content when it has been updated? Or should I return the same status for both actions?


Solution

  • TL;DR

    Use 200 OK in both cases if the distinction isn't important to clients.

    Use 201 Created upon creation, and 200 OK upon update, if the distinction is important.

    Details

    With RESTful design, there's no single, correct way of doing things, but I've often found that the original HTTP status code specification provides good guidance.

    It's always fine to return 200 OK if you don't expect the client to take separate action based on the response, but you can provide more information if you think the client is going to need it. Just be aware that clients may come to expect that of your API, so once you start providing more details, you can't easily change your mind.

    That said, if you want to return 201 Created, then according to the specification:

    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.

    As an example, you can put the location in the Location header, but you can also put it in the body of the response (but then you must document the structure and content-type of that body).

    When it comes to 204 No Content responses, they create dead ends for link-following clients, so if you're creating a true level 3 REST API then you should avoid that response type as a courtesy to clients.