Maarten Raaijmakers
Maarten Raaijmakers

Reputation: 645

API Call with Lumen + Guzzle gives error Array to string conversion

I'm trying to call https://api.binance.com/api/v3/ticker/price as a json object, however I keep getting Array to string conversion when I use json_decode. What am I doing wrong here?

<?php namespace App\Helpers;

use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Client;

class Ticker
{
    private $client;

    public function __construct()
    {
        $this->client = new Client(['base_uri' => 'https://api.binance.com/api/']);
    }

    public function update()
    {

        $response = json_decode($this->client->get('v3/ticker/price')->getBody());
        return $response;
    }
}

Upvotes: 1

Views: 1770

Answers (2)

patricus
patricus

Reputation: 62368

json_decode is turning the guzzle response string into a php array. You're then returning that array from your controller method. Whatever you return from your controller, Laravel attempts to convert it to a string. Since you've returned an array, you're getting the array to string conversion error.

Either don't decode the guzzle response, or convert it to a string or other response you'd like.

Upvotes: 0

Mathew Tinsley
Mathew Tinsley

Reputation: 6976

The getBody method on a guzzle response does not return a string, it returns a stream.

Try:

$this->client->get('v3/ticker/price')->getBody()->getContents()

Upvotes: 2

Related Questions