By default, when something throws an exception when accessing an API in Laravel, it is not always returned in a JSON response. A JSON response is returned only when the client explicitly indicates that they want to receive JSON in the response. In all other cases, plain HTML code will be returned, or even a redirect to the login page will be performed if the authorization fails.
This can make it a bit difficult to find the cause of errors for developers who have just come to Laravel. In this short article, I’ll show you how to return exceptions as JSON in Laravel for all API requests by default.
How to Return an Exception as JSON in Laravel
You can check what form an exception is returned by executing a request to /api/user. By default, you’ll see a redirect to the login page instead of an authorization error message. As I said earlier, you can add the Accept header with the value application/json to the request, then everything will work as expected. For example, in Postman:
Then the result of the request will be returned in JSON format. But there is another way. You can configure Laravel to return a JSON response for all API requests, even for exceptions. To do this, open the file app/Exceptions/Handler.php and add the method shouldReturnJson():
protected function shouldReturnJson($request, Throwable $e): bool
return parent::shouldReturnJson($request, $e) || $request->is("api/*");
This method overloads a similar method in the base class that only contains a check to see if the client expects to receive JSON in this request. We add a condition that you need to return JSON for all requests in which the URL starts with /api. After that, you can run the API request again and make sure that even in case of an error, JSON will be returned without the need to add the Accept header.