charlie
charlie

Reputation: 481

HTTP Guzzle not returning all data

I have created a function that contacts a remote API using Guzzle but I cannot get it to return all of the data available.

I call the function here:

$arr = array(
    'skip' => 0,
    'take' => 1000,
);
$sims = api_request('sims', $arr);

And here is the function, where I have tried the following in my $response variable

json_decode($x->getBody(), true)

json_decode($x->getBody()->getContents(), true)

But neither has shown any more records. It returns 10 records, and I know there are over 51 available that it should be returning.

use GuzzleHttp\Client;
function api_request($url, $vars = array(), $type = 'GET') {
    $username = '***';
    $password = '***';
    
    //use GuzzleHttp\Client;
    $client = new Client([
        'auth' => [$username, $password],
    ]);
    
    $auth_header = 'Basic '.$username.':'.$password;
    $headers = ['Authorization' => $auth_header, 'Content-Type' => 'application/json'];
    $json_data = json_encode($vars);
    $end_point = 'https://simportal-api.azurewebsites.net/api/v1/';
    
    try {
        $x = $client->request($type, $end_point.$url, ['headers' => $headers, 'body' => $json_data]);
        $response = array(
            'success' => true,
            'response' => // SEE ABOVE //
        );
    } catch (GuzzleHttp\Exception\ClientException $e) {
        $response = array(
            'success' => false,
            'errors' => json_decode($e->getResponse()->getBody(true)),
        );
    }
    
    return $response;
}

Upvotes: 0

Views: 956

Answers (1)

Pedro Caseiro
Pedro Caseiro

Reputation: 495

By reading the documentation on https://simportal-api.azurewebsites.net/Help/Api/GET-api-v1-sims_search_skip_take I assume that the server is not accepting your parameters in the body of that GET request and assuming the default of 10, as it is normal in many applications, get requests tend to only use query string parameters.

In that function I'd try to change it in order to send a body in case of a POST/PUT/PATCH request, and a "query" without json_encode in case of a GET/DELETE request. Example from guzzle documentation:

$client->request('GET', 'http://httpbin.org', [
    'query' => ['foo' => 'bar']
]);

Source: https://docs.guzzlephp.org/en/stable/quickstart.html#query-string-parameters

Upvotes: 1

Related Questions