Search code examples
resthttprfc

What status code to use when a parameter is missing in the query string?


I have an endpoint that requires a parameter passed via the query string (is a GET verb).

What is the appropriated status code to give when this parameter is missing from the request? 400 is the one? or should I respond with a 404?

[GET /search?q=ok] => 200 OK
[GET /search] => 400 Bad Request? or 404 Not Found? Or 422 Unprocessable Entity? Others?

Solution

  • TLDR It's an HTTP 400 - Bad Request.

    It's a 400 because the user did not send the Required input field.

    why not 422 - because this case fits to 400. Keeping your consumers in mind, you shouldn't go to non-popular response codes if you don't really need to.

    Cases for HTTP 404:

    1. Url which the client requested is not existing in your server (usually this will be handled by your server. Application developer usually doesn't have to do anything unless you want a nice looking 404 page or for SEO reasons).

    2. If it was a path parameter and client was looking for an entity with an id (for Example (/students/{id} and your application couldn't find such entity, you may respond with an HTTP 404.

    Let's say, user send the query parameter and you did not find any items matching the query param, make no mistake, it's still an HTTP 200 with body as an empty array or so (not a 404 unlike mentioned in the previous case). Example: /customers?lastname=unobtanium