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

dmag's avatar
Level 6

Http response "->json()" returns null, "->body()" contains data

When I try to return http response as json it returns null, while the body contains data. I've tried to add ->asJson(), ->acceptJson() - didn't help. The response header contains Content-Type: application/json.

Http::baseUrl('http://example.com')
    ->withHeaders(['DBName' => 'my-db-name'])
    ->get('/the-endpoint')->json();
// returns 'null'

Http::baseUrl('http://example.com')
    ->withHeaders(['DBName' => 'my-db-name'])
    ->get('/the-endpoint')->body();
/*
Returns:
"""
{\n
    "data": [{
        "PatientName": "Kirsten",\n
    }]\n
}
"""
*/
0 likes
7 replies
LaryAI's avatar
Level 58

It looks like you're encountering an issue where the ->json() method is returning null, even though the ->body() method shows that the response contains valid JSON data. This can happen if the JSON response is not properly formatted or if there are hidden characters that are causing the JSON parsing to fail.

Here are a few steps to troubleshoot and resolve this issue:

  1. Check for Hidden Characters: Sometimes, hidden characters (like BOM - Byte Order Mark) can cause JSON parsing to fail. You can use trim() to remove any such characters.

  2. Validate JSON Format: Ensure that the JSON response is properly formatted. You can use an online JSON validator to check the format.

  3. Manually Decode JSON: If the ->json() method is not working, you can manually decode the JSON response using json_decode().

Here is an example of how you can manually decode the JSON response:

$response = Http::baseUrl('http://example.com')
    ->withHeaders(['DBName' => 'my-db-name'])
    ->get('/the-endpoint');

$body = $response->body();
$jsonData = json_decode($body, true);

if (json_last_error() === JSON_ERROR_NONE) {
    // Successfully decoded JSON
    var_dump($jsonData);
} else {
    // JSON decoding failed
    echo 'JSON Error: ' . json_last_error_msg();
}

In this example, we first get the response body using ->body(), then manually decode it using json_decode(). We also check for any JSON decoding errors using json_last_error() and json_last_error_msg().

If the manual decoding works, it indicates that there might be an issue with how the ->json() method is handling the response. If you continue to face issues, you might want to inspect the raw response headers and body to ensure there are no anomalies.

Additionally, you can try adding the Accept header explicitly to ensure the server returns JSON:

$response = Http::baseUrl('http://example.com')
    ->withHeaders([
        'DBName' => 'my-db-name',
        'Accept' => 'application/json'
    ])
    ->get('/the-endpoint');

$jsonData = $response->json();

if ($jsonData === null) {
    // Fallback to manual decoding if ->json() returns null
    $body = $response->body();
    $jsonData = json_decode($body, true);
}

var_dump($jsonData);

By explicitly setting the Accept header, you ensure that the server knows you expect a JSON response. If ->json() still returns null, the manual decoding fallback will handle the response.

experimentor's avatar

Maybe the host / server is returning stringified json only. Please try the request with header "Accept" : "application/json" This header tells the server that we want data in json format only. Not as a string.

dmag's avatar
Level 6

@experimentor I had tried it by adding ->acceptJson() method, but after your suggestion I've added the header explicitly, here's what it returns:

[
  "data" => []
]
dmag's avatar
Level 6

but in postman the response is in json as expected, no issues there

experimentor's avatar

@dmag Is it your own server endpoint you are hitting? If yes, you may need to tweak the code there.

{\n
    "data": [{
        "PatientName": "Kirsten",\n
    }]\n
}

I think this is invalid json.

Snapey's avatar

@experimentor I think the trailing comma makes it invalid

edit checked with json formatter, and yes, the trailing comma after kirsten is the issue

Please or to participate in this conversation.