Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTTP 404 vs 400 for invalid query parameters

Here is my request URL:

http://server.com/app/user/getuser/?userId=9999

Note that userId is query parameter. Not embedded path parameter.

I understand that if the request URL is: http://server.com/app/user/getuser/9999 and the ID 9999 does not exist in database, The code 404 should be used.

BUT what HTTP status should be used for the case userId is query parameter? Right now I am returning 400 instead of 404.

like image 993
Loc Avatar asked Aug 03 '18 16:08

Loc


People also ask

What is the difference between 400 and 404?

400 is a general 'bad request'. 401 means the request was unauthorized, and 404 means no resource corresponding to the given URL can be located. These all have in common that they are deficiencies in the REQUEST, and could be, potentially, remedied by making another request.

When should I use HTTP 400?

The HyperText Transfer Protocol (HTTP) 400 Bad Request response status code indicates that the server cannot or will not process the request due to something that is perceived to be a client error (for example, malformed request syntax, invalid request message framing, or deceptive request routing).

What is the best HTTP response code for a post request with incorrect parameters?

You can send a 400 Bad Request code. It's one of the more general-purpose 4xx status codes, so you can use it to mean what you intend: the client is sending a request that's missing information/parameters that your application requires in order to process it correctly.

When should you throw a 404?

If the server does not know, or has no facility to determine, whether or not the condition is permanent, the status code 404 (Not Found) SHOULD be used instead. This response is cacheable unless indicated otherwise.


1 Answers

I would use 404 Not Found.

Why?

The RFC 7231 defines a 400 Bad Request response like this:

The 400 (Bad Request) status code indicates that the server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing).

...since your request is valid and you are just trying to access a resource that does not exist, I think a 404 Not Found status is more suitable. RFC 7231 defines its meaning like this:

The 404 (Not Found) status code indicates that the origin server did not find a current representation for the target resource or is not willing to disclose that one exists.

like image 178
Ronan Boiteau Avatar answered Oct 16 '22 06:10

Ronan Boiteau