laminas-api-tools / api-tools

Laminas API Tools module for Laminas
https://api-tools.getlaminas.org/documentation
BSD 3-Clause "New" or "Revised" License
37 stars 19 forks source link

returning JSON 404 #4

Open weierophinney opened 4 years ago

weierophinney commented 4 years ago

Since it is an API. When an endpoint does not exists (route is not found), shouldn't it return a 404 with response in JSON instead of error/404.phtml or some other HTTP code with a JSON response?


Originally posted by @rcapile at https://github.com/zfcampus/zf-apigility/issues/191

weierophinney commented 4 years ago

Apigility essentially maps routes to resources, which means that if routing does not match something, we don't know if that something should be an API resource, or a general web page; as such, returning JSON may be erroneous, if the page in question might map to an HTML response. We chose not to interfere with the normal MVC workflow and use the general tooling.

If you want to return a 404 with JSON, there are a couple of possibilities.

First, if the 404 might be due to an invalid identifier, you can either throw an exception with a 404 code, or return an ApiProblemResponse from your controller or REST resource.

Second, you can hook into the MvcEvent::EVENT_DISPATCH_ERROR, and check if the event error matches Application::ERROR_ROUTER_NO_MATCH; if it does, your listener could return an ApiProblemResponse with a 404 error code.

If this second functionality is something you feel would be a good general purpose addition to Apigility, we can consider adding a listener that users can optionally register with their Apigility applications for that purpose.


Originally posted by @weierophinney at https://github.com/zfcampus/zf-apigility/issues/191#issuecomment-305282166