Black Friday: the Laravel testing course is $149 instead of $249, through Dec 7. See the course →
logo

A nuanced opinion on validating URL request parameters

What error code should you use?

Joel Clermont
Joel Clermont
2024-05-29

From our daily Laravel tips email. Get the next one in your inbox.

I probably spend more time than I should thinking about which error code to return from various scenarios in my Laravel app.

Recently, Aaron and I were discussing this in the context of a URL path parameter that is incorrect.

For example, let's say you have a URL like PUT /api/v1/products/{product_id} where the product_id is a UUID.

If a user sends in a request with a product_id that does not exist, it's pretty obvious we should return a 404 HTTP status code. But what if they send in a product_id that is not a UUID? It's missing a few characters, or they pass in an integer instead?

At first, I was thinking this should be a 422, which is used by Laravel for validation failures. My thought was that someone building an API integration would appreciate a more specific, and therefore more helpful, error code.

But Aaron talked some sense into me and convinced me it should still be a 404. Why? Well the path parameter is part of the URL, the route into our application. If someone requests a route that doesn't exist, it should be a 404. Trying to be more helpful would actually lead to a less consistent API.

On the other hand, if a query string parameter should be a UUID, and they pass an integer, then we agree a 422 makes sense. It's not part of the routing logic. It's data sent along with the request, just like a form body, which Laravel would validate and return a 422 if there's a failure.

Consistency is good, and having a reason for why you're doing something is even better.

Here to help,

Joel

P.S. We put the same high level of thought into our deep dive on Laravel validation.

Want a tip like this in your inbox every weekday?

Each one takes less than 2 minutes to read. Join 4,000+ Laravel developers who already get them.

email
No spam. Only real-world advice.
Toss a coin in the jar if you found this helpful.