<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: Bright Onapito</title>
    <description>The latest articles on Forem by Bright Onapito (@onabright).</description>
    <link>https://forem.com/onabright</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F941171%2F8cdb5ca1-86a5-471b-b0ca-3dc73ee966d5.jpeg</url>
      <title>Forem: Bright Onapito</title>
      <link>https://forem.com/onabright</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/onabright"/>
    <language>en</language>
    <item>
      <title>How to return JSON response on API routes in Laravel</title>
      <dc:creator>Bright Onapito</dc:creator>
      <pubDate>Mon, 22 May 2023 08:19:45 +0000</pubDate>
      <link>https://forem.com/onabright/how-to-return-json-response-on-api-routes-in-laravel-1cga</link>
      <guid>https://forem.com/onabright/how-to-return-json-response-on-api-routes-in-laravel-1cga</guid>
      <description>&lt;p&gt;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. &lt;br&gt;
You then try to access a protected route through a browser which will return something like this: &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F13tq6f4jsew60c0zqp4x.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F13tq6f4jsew60c0zqp4x.png" alt="Laravel Exception when user unauthorized "&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;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. &lt;br&gt;
By default, Laravel returns header responses in HTML format.&lt;br&gt;
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 &lt;code&gt;Accept&lt;/code&gt; and setting it to &lt;code&gt;application/json&lt;/code&gt;. This would display a 'graceful' json response instead of HTML.&lt;/p&gt;

&lt;p&gt;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.  &lt;/p&gt;

&lt;h2&gt;
  
  
  1. Create a Custom Middleware
&lt;/h2&gt;

&lt;p&gt;Using the Artisan CLI, create the middleware like this:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;

&lt;span class="n"&gt;php&lt;/span&gt; &lt;span class="n"&gt;artisan&lt;/span&gt; &lt;span class="n"&gt;make&lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt;&lt;span class="n"&gt;middleware&lt;/span&gt; &lt;span class="nc"&gt;ReturnJsonResponseMiddleware&lt;/span&gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Open the middleware file located in App\Http\Middleware. &lt;br&gt;
Update the handle method to look like this:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;

&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;function&lt;/span&gt; &lt;span class="n"&gt;handle&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;Request&lt;/span&gt; &lt;span class="nv"&gt;$request&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;Closure&lt;/span&gt; &lt;span class="nv"&gt;$next&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nv"&gt;$request&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="n"&gt;headers&lt;/span&gt;&lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;&lt;span class="nf"&gt;set&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s1"&gt;'Accept'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s1"&gt;'application/json'&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nv"&gt;$next&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$request&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;What this does is that it sets the header to accept and return a json response. &lt;/p&gt;

&lt;h2&gt;
  
  
  2. Publish the Custom Middleware
&lt;/h2&gt;

&lt;p&gt;To do this, we need to add our middleware to the Laravel Kernel under the application's global HTTP middleware stack. &lt;br&gt;
To do this, open&lt;code&gt;Kernel.php&lt;/code&gt; in App\Http and add the custom middleware class:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;

&lt;span class="k"&gt;protected&lt;/span&gt; &lt;span class="nv"&gt;$middleware&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;

       &lt;span class="mf"&gt;...&lt;/span&gt;
        &lt;span class="nc"&gt;\App\Http\Middleware\ReturnJsonResponseMiddleware&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;class&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="c1"&gt;//return graceful unauthenticated message&lt;/span&gt;

    &lt;span class="p"&gt;];&lt;/span&gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

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

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight php"&gt;&lt;code&gt;

&lt;span class="p"&gt;{&lt;/span&gt;
&lt;span class="n"&gt;message&lt;/span&gt;&lt;span class="o"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"Unauthenticated"&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fvonmyu6i8pgxy4d0ajz9.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fvonmyu6i8pgxy4d0ajz9.png" alt="Graceful json response"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;I hope this was helpful. &lt;/p&gt;

</description>
      <category>tutorial</category>
      <category>laravel</category>
      <category>api</category>
      <category>webdev</category>
    </item>
  </channel>
</rss>
