3

I'm trying to read the data from an api using Guzzle 6, but have been unable to find any relevant examples. Each line returned from the api is a json object - the aim is to process each line as it is received.

The code I have so far is below, could someone advise where I have got confused?

Thanks

    ini_set('display_errors', true);

require('vendor/autoload.php');

use GuzzleHttp\Client;
use GuzzleHttp\Stream\Stream;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Psr7\Request;

$token = "1234";

$client = new Client(['base_uri' => 'https://apiurl.com'], ['stream' => true, 'debug'=>true]);


$headers = [
    'Authorization' => 'Bearer ' . $token,        
    'Accept'        => 'application/json',
];


$response = $client->request('GET', '?foo=bar', ['headers' => $headers ]);


$body = $response->getBody();
while (!$body->eof()) {
    echo $body->read(1024);
}
Tom Meredith
  • 61
  • 1
  • 4

2 Answers2

3

Turns out, after hours of testing, that it was a simple error in creating the client - the correct setup is as follows:

$client = new Client(['base_uri' => 'https://apiurl.com', 'stream' => true, 'debug'=>true]);

Tom Meredith
  • 61
  • 1
  • 4
0

Content should be accessible using :

$client = new Client([...]);
$request = $client->get($url, ['headers' => $headers ]);
$body = $response->getBody()->getContents();

You can test request success checking HTTP code using:

$code = $response->getStatusCode();

From your code, if your $response variable is correct (request correctly done), $body->getContents() should contain the response content.

Mtxz
  • 3,749
  • 15
  • 29
  • HI. Thanks, but I can't get this to work. If I use a non-stream from the same API provider, I get the json response output along with a 200 OK status code. As soon as I change to the stream endpoint, I get nothing - the script just sits there. My suspicion is that it is waiting for the end of the file before moving to the response, which of course does not come. – Tom Meredith Sep 26 '18 at 10:20
  • Did you try using postman to see if the other endpoint works? You can also set a custom timeout, and put the code in a Try/Catch block to catch the timeout and continue execution – Mtxz Sep 26 '18 at 10:34