I'm trying to develop error handling in my REST API and I'm currently working on the response codes. I haven't found a proper answer to what would be the appropriate response code for my problem.
I have routes which are managed like this in the back-end code:
$site->route([
'route' => '/{id:^[a-z]+$}'
]);
Now lets say the user inputs www.example.com/page1
which does not match the regex
pattern. What would be the correct response? I am thinking either a 404
, page not found, but I also think that a 400
response would be correct, because it describes that there was an error with the request.
I already use 404 if static URLs are invalid, so this is a question of matching dynamic parts of the URLs.
What are the field of use of both of these response codes in the case of REST APIs?
I think 404
is more appropriate.
According to the specification, 400
means:
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.
While 404
means:
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.
From client point of view, request to /page1
will result in error, because the resource page1
does not exist (no route is matched in server side).
Normally, 400
means the server has already targeted the resource, but cannot return that resource due to client error. In this scenario, server cannot target the resource if no route is matched. Anyway, if the request is sent to /123456
and the status code is 400
, what should be the error message? "Your requested URL is incorrect" sounds like 404, and "Your requested URL should follow regular expression: ...^[a-z]+$..." sounds very weird.