How to return Guzzle JSON response

Dbrandt picture Dbrandt · Sep 30, 2015 · Viewed 9.3k times · Source

I am using Guzzle to make a aSync request that returns JSON. The call is working fine and the response is ok, however:

$client = new Client();
    $promise = $client->requestAsync($requestType ,$this->url.$resource, // endpoint
        [
            'auth' => [ // credentials
                $this->username, 
                $this->password
            ],
            'json' => $payload, // the package
            'curl' => [ // some curl options
                CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
                CURLOPT_RETURNTRANSFER => true,
            ],
            'headers' => [ // custom headers
                'Accept' =>  'application/json',
                'Content-Type' => 'application/json'
            ]
        ]
    );

    $response = $promise->wait();
    echo $response->getStatusCode().'<br /><br />';
    // Error handling
    if($response->getStatusCode() != 200){
        // Error Handling
    }else{
        echo $response->getBody(true);
    }

if I echo response->getBody() I see the JSON string, but if I assign it to a property, print_r, or return it I get:

GuzzleHttp\Psr7\Stream Object ( [stream:GuzzleHttp\Psr7\Stream:private] => Resource id #245 [size:GuzzleHttp\Psr7\Stream:private] => [seekable:GuzzleHttp\Psr7\Stream:private] => 1 [readable:GuzzleHttp\Psr7\Stream:private] => 1 [writable:GuzzleHttp\Psr7\Stream:private] => 1 [uri:GuzzleHttp\Psr7\Stream:private] => php://temp [customMetadata:GuzzleHttp\Psr7\Stream:private] => Array ( ) )

I need to use the JSON to validate my response from the service. How can I do this? I have gone through the docs, but am I obviously missing something.

Essentially along the lines of assigning the json getBody output to say $json:

if($json->first_field > 0)

Any Help appreciated. Regards

Answer

Dbrandt picture Dbrandt · Sep 30, 2015

After some more research on SO I tumbled head first into this post

Guzzle 6: no more json() method for responses

Essentially doing the following will return the raw output.

return $response->getBody()->getContents();

Huge headache gone. Hope this helps someone