Michael Michael - 7 months ago 81
PHP Question

Laravel guzzle Get request to API , interaction

I'm trying to send get request to this API https://api.coinmarketcap.com/v1/ticker/bitcoin/ and it's working fine, i'm getting the object but when i try to call object properties it's giving me error:

Undefined property: GuzzleHttp\Psr7\Response::$id

This is my code:

$client = new GuzzleHttp\Client(['base_uri' => 'https://api.coinmarketcap.com/v1/ticker/']);
$response = $client->request('GET', 'bitcoin');
return $response->id;;

I don't really know how to interact with this object...


The Guzzle Response object doesn't work that way, it doesn't assume what the response content is and proxy your request for a property.

You used to be able to call $response->json(), but you can't do that anymore due to PSR-7. Instead do something like this:

$items = json_decode($response->getBody());
foreach ($items as $item) {

That endpoint returns an array of objects. So you would need to either get the first one or loop through them if there are multiple.

NOTE: If you are adding the namespace at the top of your controller like:

use \GuzzleHttp\Client;

You then in your code need only to refer to it as Client like:

$client = new Client(...);