Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

sarmadindhar's avatar

Default adding Api Request headers

Is there any way to add Accept=application/json header with every request in API by default. Because currently in every request I have to pass Accept header manually. Is there any method in laravel that adds this header by default/automatically with every request?

0 likes
6 replies
tokoiwesley's avatar

Yes, but it has to be done from the Client's end and not your Laravel app (the Resource Server). What Client are you using in this case?

sarmadindhar's avatar

@TOKOIWESLEY - Clients can access it via android or Ios I want to send a response if no header is passed. Currently It is returning html page not found instead of a specific response

tokoiwesley's avatar

@sarmadindhar you are getting 404: Page not found because the request is invalid.

Laravel APIs are RESTful and by default REST APIs require that you specify an endpoint (URL), method (GET, POST, PUT, DELETE etc ), list of headers and a body.

Headers are essential in providing meta-information about your request, therefore what you are suggesting will not work.

hamidgh83's avatar

You can create a middleware and add your default headers to the request. Here is the example:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class ApiMiddleware
{
    public function handle(Request $request, Closure $next)
    {
        $request->headers->set('Accept', 'application/json');
        $request->headers->set('Content-Type', 'application/json');

        return $next($request);
    }
}

Then add it to the middlewareGroups in App\Http\Kernel under api key:

protected $middlewareGroups = [
    'web' => [
        ...
    ],

    'api' => [
        'throttle:api',
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
        \App\Http\Middleware\ApiMiddleware::class,
    ],
];
3 likes
omarnas's avatar

@hamidgh83 I tried this method it works fine for the request header, but the issue is the request body will reach the controller empty after that. so I disabled it for now trying to find a solution

josep42ny's avatar

For anyone who still comes up with this:

From the official Laravel 12 docs

When rendering an exception, Laravel will automatically determine if the exception should be rendered as an HTML or JSON response based on the Accept header of the request. If you would like to customize how Laravel determines whether to render HTML or JSON exception responses, you may utilize the shouldRenderJsonWhen method

use Illuminate\Http\Request;
use Throwable;

->withExceptions(function (Exceptions $exceptions): void {
    $exceptions->shouldRenderJsonWhen(function (Request $request, Throwable $e) {
        if ($request->is('admin/*')) {
            return true;
        }

        return $request->expectsJson();
    });
})
1 like

Please or to participate in this conversation.