Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4072 pages
Node.js, PHP and APIs

Laravel shows an HTML error page where my REST API should send JSON

Erroran API client receives an HTML error page for a 404 or 500

Short answer

Laravel renders an exception as HTML or JSON based on the request's Accept header. A client that does not send it gets the HTML error page. Either require the header, or register shouldRenderJsonWhen for your api/* paths, and add a render callback for any exception that needs a custom JSON body.

  • Applies to Laravel 12, PHP 8.3
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Fix it fast

  1. 1Find out which cause you have

    Request a missing API URL without and with the JSON header and compare the Content-Type each time.

    curl -si http://localhost:8000/api/does-not-exist | grep -i -E '^(HTTP|content-type)'
    curl -si http://localhost:8000/api/does-not-exist -H 'Accept: application/json' | grep -i -E '^(HTTP|content-type)'
  2. 2Match what you see, then jump to its fix

    1. 1The same URL gives JSON with the header and HTML without it.The client does not send Accept: application/jsonFix
    2. 2The JSON arrives, but its shape (message, status) is not what your clients expect.You want your own JSON body for a specific exceptionFix
    3. 3A 500 shows file paths and stack traces.APP_DEBUG is on, so errors show a debug page or detailsFix

What does the error look like?

  • an API client receives an HTML error page for a 404 or 500
  • a fetch or mobile client fails to parse the response body as JSON

Cause 1 of 3

The client does not send Accept: application/json

1Check

When rendering an exception Laravel determines automatically whether to return HTML or JSON from the Accept header of the request.

curl -si http://localhost:8000/api/does-not-exist | grep -i content-type

2Fix

Make the API client send the header. If you cannot control the clients, force JSON for your API paths.

// bootstrap/app.php
use Illuminate\Http\Request;
use Throwable;

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

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

3Verify

Request the missing URL without the header.

curl -si http://localhost:8000/api/does-not-exist | grep -i content-type

Confirmed by laravel.com

Did this fix it?

Cause 2 of 3

You want your own JSON body for a specific exception

1Check

The render method of the exception configuration takes a closure typed with the exception class. If it returns nothing, Laravel's default rendering is used.

grep -n "withExceptions" -A12 bootstrap/app.php

2Fix

Return a JSON response for the exception you want to customize, scoped to the API paths.

use Illuminate\Http\Request;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

->withExceptions(function (Exceptions $exceptions): void {
    $exceptions->render(function (NotFoundHttpException $e, Request $request) {
        if ($request->is('api/*')) {
            return response()->json([
                'message' => 'Record not found.'
            ], 404);
        }
    });
})

3Verify

Call a missing API URL and read the body.

curl -si http://localhost:8000/api/does-not-exist -H 'Accept: application/json'

Confirmed by laravel.com

Did this fix it?

Cause 3 of 3

APP_DEBUG is on, so errors show a debug page or details

1Check

The debug option of config/app.php follows the APP_DEBUG environment variable. In production it should be false, since true can expose sensitive configuration.

grep -n APP_DEBUG .env

2Fix

Set APP_DEBUG=false in the production .env and clear the config cache.

APP_DEBUG=false

3Verify

Rebuild the config cache and trigger an error.

php artisan config:cache

Confirmed by laravel.com

Did this fix it?

How do I stop it coming back?

  • Document that every API call must send Accept: application/json.
  • Keep one exception-to-JSON mapping in bootstrap/app.php, so every route answers in the same shape.
  • Keep APP_DEBUG false on production and test error responses in staging.

Sources

How was this page made?

I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.

Which stack is behind this page?

Projects of mine built on the same technologies:

Related fixes

Back end

composer require maatwebsite/excel fails to install

Composer says the package needs an older PHP than the one installed

Composer refuses maatwebsite/excel when the PHP version or a PHP extension does not match what the package and PhpSpreadsheet need.

3 causes, each with a fix

Back end

composer require laravel/horizon fails: ext-pcntl is missing

laravel/horizon v1.1.0 requires ext-pcntl * -> the requested PHP extension pcntl is missing from your system

Horizon needs the pcntl extension, and Composer refuses to install it where PHP lacks that extension.

3 causes, each with a fix

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.