phplaravelguzzle

How to get data from Guzzle and API response in Laravel


I am new to working with an API. I am using guzzle and Laravel. How to I output specific data such as just the actor's name and image?


    $client = new \GuzzleHttp\Client();

    //$client = new GuzzleHttpClient();

    $response = $client->request('GET', 'https://imdb232.p.rapidapi.com/api/actors/get-bio?nm=nm0000573', [
    'headers' => [
        'x-rapidapi-host' => 'imdb232.p.rapidapi.com',
        'x-rapidapi-key' => 'xxxxxx',
    ],
]);

    echo $response->getBody();

  {"data":{"name":{"__typename":"Name","id":"nm0000573","nameText":{"text":"Dolly Parton"}

Here is the data for the image.

"primaryImage":{"__typename":"Image","id":"rm2099682048","url":"https://m.media-amazon.com/images/M/MV5BMTQxNjI5MjI2NV5BMl5BanBnXkFtZTYwMzExMzI1.V1.jpg",


Solution

  • Instead of echoing the response, replace it with the line below

    $data = json_decode($response->getBody(), true);
    
    /*
    $data will be a php associative array with the data
      {"data":{"name":{"__typename":"Name","id":"nm0000573","nameText":{"text":"Dolly Parton"}
    */
    
    $actorName = $data['data']['name']['nameText']['text'];
    
    echo $actorName;
    

    Also, I noticed that there is no image field in the sample response you specified