What HTTP error code for failure to create a new resource because a parent entity is gone

前端 未结 2 1846
-上瘾入骨i
-上瘾入骨i 2021-02-13 13:13

Say i have an API exposing two related resources, Company which has many Employees.

Say I create a new Company: POST http://domain/api/company/ which returns something l

2条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-13 13:53

    Not a 500, because there is no problem with the server.

    I would suggest 409 Conflict.

    From the RFC:

    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.

    It doesn't exactly match your case, but it is very close IMHO.

    For example the server could tell you the parent resource does not exist for you to post to, and you can "resubmit" the employee to a different company. :)

提交回复
热议问题