Reputation: 4048
I create an API using ZF2. The server's response should contains only JSON. It should be only JSON if there is an error or 404 or 403 and in other cases. Now, by default ZF2 is tryong to return HTML. I use ZendSkeletonApplication
Upvotes: 1
Views: 608
Reputation: 9857
ZF2 raises an error by triggering specific events such as MvcEvent::EVENT_DISPATCH_ERROR
or MvcEvent::EVENT_RENDER_ERROR
when an exception is thrown.
The Zend\Mvc\View\Http\ExceptionStrategy
class attaches a number of listens to these events so the HTML error page can be generated.
To return a JSON error message you can attach a your own custom exception strategy, with a higher priority, and check if the response should be JSON
Upvotes: 3
Reputation: 1236
Unless there's a specific reason you chose the mvc skeleton app as a starting point, you might consider switching to https://apigility.org skeleton. This is also a ZF app, but it is built to be pure json api.
Upvotes: 1
Reputation: 10202
In your controller, the easiest way is to return an instance of Zend\View\Model\JsonModel
. For example:
$model = new JsonModel(array(
'httpStatus' => 403,
'title' => 'Forbidden',
'message' => 'You are not authorized to access this page.'
));
return $model;
Upvotes: 2