DEV Community

Bright Onapito
Bright Onapito

Posted on

How to return JSON response on API routes in Laravel

If you work with Laravel, you could have found yourself in a situation where you have written your API Controllers, set up your API routes and setup authentication (for example, using Sanctum) to protect your routes from unauthorized access.
You then try to access a protected route through a browser which will return something like this:

Laravel Exception when user unauthorized

First of all this is a good thing because it means your API route is protected and can only be accessed by authenticated users. However, it doesn't look pretty at all.
By default, Laravel returns header responses in HTML format.
If you access the API route/endpoint using an API testing tool like Postman, Fiddler, RESTer, etc., you could easily update the Header by adding an entry called Accept and setting it to application/json. This would display a 'graceful' json response instead of HTML.

To change this default behaviour programmatically, we would want Laravel to return a json response telling the user that they are unauthenticated. How do we achieve this? It is actually pretty simple to do. Let's see how.

1. Create a Custom Middleware

Using the Artisan CLI, create the middleware like this:

php artisan make:middleware ReturnJsonResponseMiddleware
Enter fullscreen mode Exit fullscreen mode

Open the middleware file located in App\Http\Middleware.
Update the handle method to look like this:

public function handle(Request $request, Closure $next)
        $request->headers->set('Accept', 'application/json');
        return $next($request);
Enter fullscreen mode Exit fullscreen mode

What this does is that it sets the header to accept and return a json response.

2. Publish the Custom Middleware

To do this, we need to add our middleware to the Laravel Kernel under the application's global HTTP middleware stack.
To do this, openKernel.php in App\Http and add the custom middleware class:

protected $middleware = [

        \App\Http\Middleware\ReturnJsonResponseMiddleware::class, //return graceful unauthenticated message

Enter fullscreen mode Exit fullscreen mode

That's it! Now when a user tries to access a protect API route through the browser, they will get a json response:

message: "Unauthenticated"
Enter fullscreen mode Exit fullscreen mode

Graceful json response

I hope this was helpful.

Top comments (2)

ekqt profile image
Hector Sosa • Edited

Laravel has been showing up more and more on my feed! Great post! I'd recommend trying to enable syntax highlighting for your posts and framing your screenshots to make sure you keep your readers engaged.

We've built a simple OSS tool to help with screenshots. Take a look at it and let us know what you think. I'd appreciate giving it a Star on GitHub if you find it helpful! Cheers!

onabright profile image
Bright Onapito

Hello @ekqt , thanks for the feedback! I will surely checkout your tool.
Thanks again.