Laravel Tutorials

Always Render API Exceptions as JSON in Laravel

Published
Always Render API Exceptions as JSON in Laravel image

Have you ever enforced returning JSON on API requests for exceptions using a custom middleware like the following:

class ForceJsonResponse
{
public function handle(Request $request, Closure $next)
{
$request->headers->set('Accept', 'application/json');
 
return $next($request);
}
}

Laravel 11 gives you a handy way to do this without any extra middleware. I think it's really nice if you are using a web browser to test API routes and always get JSON even without setting the Accept header to application/json or using the above middleware:

// bootstrap/app.php
 
return Application::configure(basePath: dirname(__DIR__))
 
//...
 
->withExceptions(function (Exceptions $exceptions) {
$exceptions->shouldRenderJsonWhen(function (Request $request, Throwable $e) {
if ($request->is('api/*')) {
return true;
}
 
return $request->expectsJson();
});
})->create();

Using the shouldRenderJsonWhen() method, this code ensures that any exceptions thrown during an API request are rendered as JSON. Besides exceptions, it's up to you to ensure non-error responses return JSON.

This tip comes straight from the documentation, which also has some excellent tips on throttling exceptions, customizing error responses, and more!

Paul Redmond photo

Staff writer at Laravel News. Full stack web developer and author.

Sponsored

laravelcloud logo
Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Visit Laravel Cloud

The latest

View all →
PayZephyr: One Payment API for Stripe, Paystack, and PayPal image

PayZephyr: One Payment API for Stripe, Paystack, and PayPal

Read article
Bifrost Turns One With AI Builds and New Workflows image

Bifrost Turns One With AI Builds and New Workflows

Read article
Preview Blade Templates in macOS Finder with Quick Blade image

Preview Blade Templates in macOS Finder with Quick Blade

Read article
Artisan Debugging Commands in Laravel Telescope 5.24.0 image

Artisan Debugging Commands in Laravel Telescope 5.24.0

Read article
Queue totalSize() and JobInterrupted Event in Laravel 13.31 image

Queue totalSize() and JobInterrupted Event in Laravel 13.31

Read article
Find Unexpected Test Inputs with Fuzz for Pest image

Find Unexpected Test Inputs with Fuzz for Pest

Read article