I would add a middleware checking if the app is down (app()->isDownForMaintenance()) and if it is, setting response to whatever you want.
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?
@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.
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'
]);
}
});
}
@imhuync doenst this trigger on every exception, not only during maintenance?
@Bvanhaastrecht oh, yes. I wrapped into a test for maintenance mode on
@realtebo ah, my toughts exactly. Im trying to find the best way to test for maintenance mode for v9, how are you testing it?
return file_exists($this->storagePath().'/framework/down');
@realtebo interesting, didnt knew those files were generated during down.
Im using:
if (app()->maintenanceMode()->active()) {
}
Thanks for sharing.
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);
}
}
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.