Consum Guzzle response with slim

I try to get api data with Guzzle client. But i don’t know how to parse it and send response to view.
$promise = $this->client->getAsync(‘apiCall’);
$response = $promise->wait();

return $response->getBody();

give me a string.
If I use
return $response->withJson();
give string to.
Any idea?

Thx

$client = new \GuzzleHttp\Client(); 
$response = $client->request('GET', 'http://httpbin.org/get'); 

echo $response->getStatusCode(); // 200 
echo $response->getReasonPhrase(); // OK 
echo $response->getProtocolVersion(); // 1.1

SLIM

$body = $response->getBody(); // from Guzzle

// for example body is `array`
return $response->withJson($body);

// for example body is `json`
return $response->withHeader('Content-Type', 'application/json')->write($body);
2 Likes

In case of asynchronous request

$promise = $this->client->getAsync(‘apiCall’);

$promise->then(
    function (ResponseInterface $response) use ($responseSlim) {
        //success
        $body = $response->getBody();

        // for example body is `array`
        return $responseSlim->withJson($body);

        // for example body is `json`
        return $responseSlim->withHeader('Content-Type', 'application/json')->write($body);
    },
    function (RequestException $e) {
        //error
        echo $e->getMessage() . "\n";
        echo $e->getRequest()->getMethod();
    }
);
1 Like

Thanks Mikalay, is awesome.

Here my solution:

$promise = $this->client->getAsync(‘https://api…’);
$result = $promise->wait(true);
$result = json_decode($result->getBody());

// Do somthing with result

return $response->withJson($result);