LHA
LHA

Reputation: 9655

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.

Upvotes: 20

Views: 19546

Answers (2)

Fabrizio FDG Siculo
Fabrizio FDG Siculo

Reputation: 11

In my opinion, if the "user" is the resource, a better way to expose that resource is to use a URL like this: http://server.com/app/user/9999

Query parameters are best for searching a dataset, where an empty answer is still valid (200).

But, if you can't change the URL, 404 in this case is a valid option.

Upvotes: 1

Ronan Boiteau
Ronan Boiteau

Reputation: 10138

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.

Upvotes: 21

Related Questions