PHP

guzzle is php http client that is used to send request to web services.

Installation :

First download guzzle files from here and put those files in application/libraries folder.

Now load this library in controller’s constructor function.

 $this->load->library('guzzle'); 

if there is an error that library is not loaded, then rename guzzle.php in application/libraries to GUZzle.php and change the name correspondingly.

$this->load->library('GUZzle');

How to use guzzle on codeigniter?

POST request

How to pass authorization with bearer token request in guzzle http client.

How to

//create client and give it a base url of api
$client = new GuzzleHttp\Client(['base_uri' => 'https://api.dummy.com/v3/']);
try {
          $response = $client->request(
                  'POST', 'users', [
                  'headers' => [ 'Authorization' => "Bearer token_key"],
                  'json' => ['username' => $username]
                 ]);
                 $responseBodyAsString = $response->getBody()->getContents();
                 print_r(json_decode($responseBodyAsString));
 } catch (GuzzleHttp\Exception\BadResponseException $e) {  
            $response = $e->getResponse(); 
            echo $response->getStatusCode(); 
            $responseBodyAsString = $response->getBody()->getContents();
            print_r($responseBodyAsString);        
 }

Notes : headers must be third parameter if working with authorization.

Leave a comment