HTTP response code for POST when resource already exists
Solution 1:
My feeling is 409 Conflict
is the most appropriate, however, seldom seen in the wild of course:
The request could not be completed due to a conflict with the current state of the resource. This code is only allowed in situations where it is expected that the user might be able to resolve the conflict and resubmit the request. The response body SHOULD include enough information for the user to recognize the source of the conflict. Ideally, the response entity would include enough information for the user or user agent to fix the problem; however, that might not be possible and is not required.
Conflicts are most likely to occur in response to a PUT request. For example, if versioning were being used and the entity being PUT included changes to a resource which conflict with those made by an earlier (third-party) request, the server might use the 409 response to indicate that it can't complete the request. In this case, the response entity would likely contain a list of the differences between the two versions in a format defined by the response Content-Type.
Solution 2:
According to RFC 7231, a 303 See Other MAY be used If the result of processing a POST would be equivalent to a representation of an existing resource.
Solution 3:
Personally I go with the WebDAV extension 422 Unprocessable Entity
.
According to RFC 4918
The
422 Unprocessable Entity
status code means the server understands the content type of the request entity (hence a415 Unsupported Media Type
status code is inappropriate), and the syntax of the request entity is correct (thus a400 Bad Request
status code is inappropriate) but was unable to process the contained instructions.
Solution 4:
It's all about context, and also who is responsible for handling duplicates in requests (server or client or both)
If server just point the duplicate, look at 4xx:
- 400 Bad Request - when the server will not process a request because it's obvious client fault
- 409 Conflict - if the server will not process a request, but the reason for that is not the client's fault
- ...
For implicit handling of duplicates, look at 2XX:
- 200 OK
- 201 Created
- ...
if the server is expected to return something, look at 3XX:
- 302 Found
- 303 See Other
- ...
when the server is able to point the existing resource, it implies a redirection.
If the above is not enough, it's always a good practice to prepare some error message in the body of the response.