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

realtebo's avatar

Maintenance mode: how to return a json when called /api/* routes?

All my APIs return json.

I created a catch-all for api/* routes to return a json equivalent of 404

I wanto my website be able to return a json also when in maintenance mode. Actually it returns an html page.

Is there a way?

0 likes
10 replies
RoboRobok's avatar

I would add a middleware checking if the app is down (app()->isDownForMaintenance()) and if it is, setting response to whatever you want.

1 like
Sti3bas's avatar

@realtebo it should work by default if \App\Http\Middleware\CheckForMaintenanceMode::class is added to middleware array in App\Http\Kernel.

If it's there and you are still getting HTML back, check if you're passing Accept: application/json header when sending a request.

2 likes
imhuync's avatar

With Laravel 9.x

app/Exceptions/Handler.php
use Symfony\Component\HttpKernel\Exception\HttpException;
...
public function register()
    {
       ...
        $this->renderable(function (HttpException $e, $request) {
            if ($request->is('api/*')) {
                return response()->json([
							'msg' => 'Maintenance'
				]);
            }
        });
    }
2 likes
Bvanhaastrecht's avatar

@realtebo ah, my toughts exactly. Im trying to find the best way to test for maintenance mode for v9, how are you testing it?

Bvanhaastrecht's avatar

@realtebo interesting, didnt knew those files were generated during down.

Im using:

if (app()->maintenanceMode()->active()) {
}

Thanks for sharing.

omysurya's avatar

If you use laravel 5.x you can modified in:

app/Exceptions/Handler.php

on method render like this:

public function render($request, Exception $exception)
    {
        if($request->is("api/*")){
            return response()->json(['api_status' => 0, 'api_message' => 'We are still under maintenance', 'error' => 'Maintenance'], 503);
        }else {
            return parent::render($request, $exception);
        }
    }
1 like
lexxyungcarter's avatar

In Laravel 11+

// bootstrap/app.php

...
return Application::configure(basePath: dirname(__DIR__))
->withExceptions(function (Exceptions $exceptions) {
        $exceptions->respond(function (Response $response, Throwable $exception, Request $request) {

            // catch on maintenance mode and return correct error on json response
            if ($request->wantsJson() && $response->getStatusCode() === 503) {
                return response()->json([
                    'message' => 'We are updating our system. Please try again in a few seconds.',
                ], 422);
            }

            return $response;
        })

...

Please or to participate in this conversation.