HTTP response code when resource creation POST fai

2019-04-19 00:22发布

问题:

Imagine we have an API where a new Employee can be created through a POST to

www.example.com/api/employees

An employee could be described as,

{
  name: "John Smith",
  tax_number: "ABC123"
}

The tax number is universally unique for all humans. If a create were made, and a record already existed in which the name and tax number matched an existing record, it is safe to assume the requester would like a reference to that record returned (with it's internal id and other data the client may not have, eg. created at, updated at).

What would the HTTP status code be for returning that resource? I suppose a redirect could be used with a return of just the id, but I'd prefer to enclose the entire object in the response.

This case is unique to a simple duplicate error, in the sense that if a duplication is attempted it means the record you wish to create already exists- as opposed to it conflicting with an existing record.

回答1:

I think if you Post a resource to an API, you expect a code 201 that will state that the resource was created, and the body will (can) contain the resource. Otherwise you first have to check if the resource is already created, but this will need two calls.

otherwise, you have the status code 409 :

The request could not be completed due to a conflict with the current state of the resource.

[Edit] after reading on Restfull Web Apis from amundsen, Ruby and Richardson

Best would be to use the 409 status code that states that there is a conflict with a resource that exists on the server. Put the url of that "conflicted" resource in the Location Header of the response and add a message of the conflict in the body



回答2:

There is a 409 Conflict response code, that is commonly used to let the client know such entity already exists on the server. It might not be very intuitive to have to parse the body of an error response but if you specify this in your API documentation there shouldn't be a problem (to put the info about the original entry in the response body).