Swarnadeep
Swarnadeep

Reputation: 341

Get Api Data using Guzzle client

I am Trying to call data from API which working fine in Postman and jquery , it has a API key name "APP_KEY" which must be sent as a header or else the data of the API can not be accessed ,I am trying to get the data using Guzzle HTTP Client But it is not sending the header,

Here is the Header that needs to be passed in:

APP_KEY=>QAWLhIK2p5

Here is the Controller Part:

$client = new Client();
      $body['headers']= array('APP_KEY'=>'QAWLhIK2p5');
      $response = $client->GET('http://localhost:1080/busy/public/api/material',$body);
      //dd($response->getStatusCode());

      print_r($data = $response->getResponse()->getContents());

Just tell me please how can I send the header with the Link to API

Any Help would be highly appreciated

Here is the Postman ssenter image description here

Upvotes: 0

Views: 2791

Answers (1)

bhucho
bhucho

Reputation: 3420

You should use guzzle as a tag as well, I would have answered that day, you need to change your code,

use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;


public function yourFunction()
{
    try {
        $client = new Client();
        $guzzleResponse = $client->get(
                'http://localhost:1080/busy/public/api/material', [
                'headers' => [
                    'APP_KEY'=>'QAWLhIK2p5'
                ],
            ]);
        if ($guzzleResponse->getStatusCode() == 200) {
            $response = json_decode($guzzleResponse->getBody(),true);
        }
        
    } catch (RequestException $e) {
        // you can catch here 400 response errors and 500 response errors
        // see this https://stackoverflow.com/questions/25040436/guzzle-handle-400-bad-request/25040600
    } catch(Exception $e){
        //other errors 
    }
}

It is as easy as that, for more info, just see docs

Upvotes: 2

Related Questions