0
votes

Using Guzzle, I'm consuming some external apis in JSON format, usually I get the data with

$data = $request->getBody()->getContents();

But i can't get data from this different api. It seems the data doesn't come in a 'Response Body'.

This api call works: https://i.ibb.co/80Yk6dx/Screenshot-2.png

This doesn't work: https://i.ibb.co/C239ghy/Screenshot-3.png

public function getRemoteCienciaVitaeDistinctions()
{
    $client = new Client(['headers' => ['Accept' => 'application/json']]);

    $request = $client->get(
        'https://................/',
        [
            'auth'          => ['...', '...'],
        ]

    );

    $data = $request->getBody()->getContents();
    return $data;
}
1
Your question is incomplete, what library are you using ? is it guzzle ?Supun Praneeth
yes sorry, is Guzzle.João Domingues
what this is returns: $request->getBody()->getContents() and what should actually return ?Supun Praneeth
it returns an empty string and it should return a json with dataJoão Domingues
try this to check whether your code is working https://reqres.in/api/products/3 this is return sample json code. remove your authSupun Praneeth

1 Answers

0
votes

the second call is working fine, but the response is empty, as we can see in Screenshot-3, the Total = 0, so the response from this API is empty.

to handle that properly I suggest you this modification for your method :

public function getRemoteCienciaVitaeDistinctions()
{
    $client = new Client(['headers' => ['Accept' => 'application/json']]);

    $request = $client->get(
        'https://................/',
        [
            'auth'          => ['...', '...'],
        ]

    );

    //Notice that i have decoded the response from json objects to php array here.

    $response = json_decode($request->getBody()->getContents());

    if(isset($response->total) && $response->total == 0) return [];

    return $response;
}

please check the documentation of the API that you are using