HTTP status while POST with incorrect data (using id of resource which does not exist)

后端 未结 3 2057
失恋的感觉
失恋的感觉 2021-02-10 04:43

What would be the correct HTTP status to return when I am performing the POST request to create a new user, but one of its parameters is incorrect - the company

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-10 05:16

    404 Not Found is a problematic status to return for a POST request. It implies the resource you are sending the request to doesn't exist; the caller got the URL wrong.

    The most obvious (and generic) answer is: 400 Bad Request

    This just indicates there is something wrong with your request (the fault lies with the caller not the server) and then express the specific detail of what went wrong in your response body. This is typically how request validation is handled.


    The ideal answer is to make it so you add a user by sending a request to the company they are a member of:

    POST /company/34
    Content-Type: application/json
    {
        "username": "newuser",
        "age": 99
    }
    

    This means the caller has to find a valid company resource to send the request to. If company/34 doesn't exist, a 404 Not Found response is appropriate; you tried adding a user to a company which does not exist.

    This does mean your API has to be structured with resource semantics and a user has to belong to exactly one company.

提交回复
热议问题