Guzzle returns stream empty body instead of json body
Solution 1
getBody()
returns a stream. If you want to get all the content at once you can use getContents()
method and decode json while at it (if you need to)
$payload = json_decode($response->getBody()->getContents());
Further reading - Guzzle Responses
Solution 2
If $response->getBody()->getContents()
doesn't work for you, try:
$response->getBody()->__toString();
As mentioned here, sometimes getContents
's stream pointer is already at the end of stream and then it returns empty response, but __toString
resets it by default.
Emeka Mbah
I am a professional Full Stack Web Developer with over 10 years expertise in professional web application development; 6 years as Full Stack PHP/Laravel Developer with track record of tackling challenges, providing solutions and beating deadlines. I used: PHP, MySQL, Laravel, Angular, JQuery, Vue, GulpJs, TDD, HTML, CSS & CSS3, MySQL, Linux, Apache, API, Bootstrap, Git, Html5, Nginx, SVN, Team leadership, WordPress I am available for hire for projects or permanent employment.
Updated on December 21, 2021Comments
-
Emeka Mbah over 2 years
When I use Postman to make an API call I receive a JSON object..which is what I expected.
However When I make same call with Guzzle like so:
$client = new \GuzzleHttp\Client(['base_uri' => 'https://api.dev/']); $response = $client->request('GET', 'search', [ 'verify' => false, ]); var_dump($response->getBody()); //null var_dump($response); //returns below
I get dump below from Guzzle
Response {#304 ▼ -reasonPhrase: "OK" -statusCode: 200 -headers: array:8 [▼ "Server" => array:1 [▶] "Content-Type" => array:1 [▼ 0 => "application/json" ] "Transfer-Encoding" => array:1 [▶] "Connection" => array:1 [▶] "Cache-Control" => array:1 [▶] "Date" => array:1 [▶] "X-RateLimit-Limit" => array:1 [▶] "X-RateLimit-Remaining" => array:1 [▶] ] -headerNames: array:8 [▼ "server" => "Server" "content-type" => "Content-Type" "transfer-encoding" => "Transfer-Encoding" "connection" => "Connection" "cache-control" => "Cache-Control" "date" => "Date" "x-ratelimit-limit" => "X-RateLimit-Limit" "x-ratelimit-remaining" => "X-RateLimit-Remaining" ] -protocol: "1.1" -stream: Stream {#302 ▼ -stream: stream resource @15 ▼ wrapper_type: "PHP" stream_type: "TEMP" mode: "w+b" unread_bytes: 0 seekable: true uri: "php://temp" options: [] } -size: null -seekable: true -readable: true -writable: true -uri: "php://temp" -customMetadata: [] } }