4

Possible Duplicate:
REST response code for invalid data

Have the following REST resource:

POST /user/{primary_key}

The resource is intended to work like an "ADD/UPDATE" operation. This means that it can be used to:

  • Create a new user
  • Update information on an existing user

If a client wanted to create a new user, some information is required:

POST user/{pimary_key}
Paylod:
 - Username - (must be unique)
 - Password

If a client wants to simply update an existing user, the call only needs to include the primary key and the new/changed information. For example:

POST user/{pimary_key}
Paylod:
 - favorite hamburger type

This situation creates the potential for several requests from the client that are invalid:

  • CONFLICT - The client updates an existing user attempting to change the username to a value that is already in use by a different user.
  • MISSING INFORMATION - The client attempts to create a new user without including necessary information such as the username and password.

What are the correct HTTP response codes to return in these cases?

Thanks so much!

Community
  • 1
  • 1
PepperoniPizza
  • 7,243
  • 8
  • 49
  • 86

2 Answers2

13
  1. code 201 for created user, quite obvious
  2. 400 for incorrect input parameters is the most suitable, google API uses it
  3. seems 409 the best for conflicting situation like yours

I would only recommend to separate creation and editing, and use different methods for them - POST to create, PUT to update. What if the user was going to modify something, but had a typo? It is better to show an error

allergic
  • 392
  • 2
  • 6
6

Here's a good table of "typical" HTTP responses to RESTful operations.

From that table, here's what's recommended for POST operations:

200 (OK) - if an existing resource has been updated
201 (created) - if a new resource is created
202 (accepted) - accepted for processing but not been completed (Async processing)

301 (Moved Permanently) - the resource URI has been updated
303 (See Other) - e.g. load balancing

400 (bad request) - indicates a bad request
404 (not found) - the resource does not exits
406 (not acceptable) - the server does not support the required representation
409 (conflict) - general conflict     
412 (Precondition Failed) e.g. conflict by performing conditional update
415 (unsupported media type) - received representation is not supported

500 (internal server error) - generic error response
503 (Service Unavailable) - The server is currently unable to handle the request
CAbbott
  • 7,998
  • 4
  • 29
  • 38