简体   繁体   中英

Which is the proper response code for this scenario - 207 vs 400 status code

I am designing the API where all the following three cases are possible

  1. All the inputs in the array are correct, so this API will return the 200 status code

    Sample output: 200 Status code

    [{ "status" : "success", "value" : "some response" }, { "status" : "success", "value" : "some response" }]
  2. Few inputs in the array are correct, so this API will return the 207 Multi-Status code

    Sample output: 207 Multi-Status code

    [{ "status" : "success", "value" : "some response" }, { "status" : "fail", "value" : "reason for failure" }, { "status" : "success", "value" : "some response" }]
  3. All the inputs are wrong in the array. In this case do I need to send the 400 Bad Request (OR) 207 status code ?

    Because if I send the 400 Bad Request then the response format will not be consistent like below

    Sample Output: 400 Status code

    {"errorcode" : "XXXXXX", "message" : "It is failed due to invalid inputs. Input must contain XXXX"}

In Case 3, do I need to send the 400 status code response or 207 status code response with all the status as 'FAIL'. Which is correct and consistent?

There is a huge difference between 2xx and 4xx codes.
2xx like 207 means the request is valid and returns values (success or fails).
However 4xx codes like 400 means that client sent an invalid request.

For instance if you have to provide at least one input in the array and client request with an empty array, it's a bad request.
In your case, the request looks valid and you have a mixed behavior of 2xx and 4xx.

If client is able to use part of your results then it's a 207, if he can use successes without failures then the result is 2xx. If he can't and he needs each input to be valid then it's a 4xx as the request should contains only valid inputs (resulting in success only).

For instance in case 3, a 400 makes sense as user can't continue his process with failures only.
You should be able to format this error by adding a property "details" containing your array of input's failures like

400
{
    "errorcode" : "XXXXXX",
    "message" : "Only invalid inputs. Input must contain XXXX",
    "details" : [{
        "status" : "fail",
        "value" : "reason for failure"
    }, {
        "status" : "fail",
        "value" : "reason for failure"
    }, {
        "status" : "fail",
        "value" : "reason for failure"
    }]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM