Laravel response()->json returns html page on server in case of validation errors

737 Views Asked by At

I have a Laravel 8 API application. Below is my example test method in the controller which return status 422 with invalid data JSON response.

public function testInvalid()
    {
        $arrResponse = [
            'success'    => false,
            'message'    => 'message',
            'data'       => [],
            'errors'     => ['error'],
            'error_code' => 422,
        ];

        return response()->json($arrResponse, 422);
    }

the above should return the JSON response in postman:

{
    "success": false,
    "message": "message",
    "data": [],
    "errors": [
        "error"
    ],
    "error_code": 422
}

But it only works on the local machine.

When I run same on the server it returns the Unprocessable entity HTML page.

But if I update it to 200 OK response code with the same response format. then it returns JSON response from the server too.

        return response()->json($arrResponse, 200);

all other valid request works fine and returns JSON response from the server.

Is it something I need to check on Apache web-server configuration?

Note: I tried passing Accept: application/json and Content-Type: application/json headers in postman request. still the same.

1

There are 1 best solutions below

1
Repox On

This is due to the Accept header of your request.

If not provided, Laravel defaults to Accept: text/html and error handling will provide you with a response matching your accept header.

By providing Accept: application/json with your request headers, Laravel will return the error response as JSON as well.