Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

understanding REST Response and HTTP status code

I wanted to know how I should respond in my REST API.

Valid Example:

http://blah.com/api/v1/dosomething/123

The above is a valid request and currently I have a HTTP Status of 200 with a JSON response

{
    "dosomething": {
        "status": "OK",
        "results": "123"
    }
}

Now my question is, if the parameter passed is not valid ( I'm expecting a string of whole numbers ), do I return a HTTP Response of 200 and pass the error status back in the JSON response or should I pass something like a HTTP 400 response ( Bad request ) and list the error / issue with the request in the JSON response?

Error Example:

http://blah.com/api/v1/dosomething/123a

JSON Response:

{
    "dosomething": {
        "status": "ERROR",
        "errors": [
            "Value passed: |123a| must be a integer."
        ]
    }
}

Again my question is should I pass a 200 or 400 HTTP status on the request where the parameter passed is not what I'm expecting? Or should this always be a 200 response as the request is working?

What is considered best practice?

like image 541
Phill Pafford Avatar asked Oct 27 '25 15:10

Phill Pafford


1 Answers

Use 404. Always. 404. To do otherwise is to misunderstand the nature of a URI and a resource. If http://blah.com/api/v1/dosomething/ identified the resource, and 123a were merely a parameter to it, then other codes could make sense. But it doesn't: http://blah.com/api/v1/dosomething/123 identifies the resource. If no such resource exists, return 404 Not Found.

You might possess some implementation detail that handles both resources http://blah.com/api/v1/dosomething/123 and http://blah.com/api/v1/dosomething/123a, but it is not the resource. From Roy Fielding's dissertation:

"The resource is not the storage object. The resource is not a mechanism that the server uses to handle the storage object. The resource is a conceptual mapping -- the server receives the identifier (which identifies the mapping) and applies it to its current mapping implementation (usually a combination of collection-specific deep tree traversal and/or hash tables) to find the currently responsible handler implementation and the handler implementation then selects the appropriate action+response based on the request content. All of these implementation-specific issues are hidden behind the Web interface; their nature cannot be assumed by a client that only has access through the Web interface."

like image 63
fumanchu Avatar answered Oct 29 '25 04:10

fumanchu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!