DEV Community

Dallington Asingwire
Dallington Asingwire

Posted on • Updated on

Using Guzzle http client to send api requests to Laravel API.

Introduction
A Guzzle is a PHP HTTP client that makes it easy to send HTTP requests with data, headers and trivial to integrate with web services. Guzzle is a simple interface for building query strings, POST requests, streaming large uploads, streaming large downloads, using HTTP cookies, uploading JSON data, etc.

Basically, GuzzleHttp helps to make requests to external api to get, post, update or delete data. Assuming you already have your api(could have been implemented in any language), I will demonstrate how to use it to make post, get, update and delete requests.

First of all, we need to install guzzlehttp in our laravel project using composer by running the command below in our project root directory.

composer require guzzlehttp/guzzle
Enter fullscreen mode Exit fullscreen mode

In your laravel class or controller, import GuzzleHttp Client as follows;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Psr7\Request;
Enter fullscreen mode Exit fullscreen mode

GET METHOD

public static function getHttpHeaders(){

       $bearerToken = 'your-bearer-token';
       $headers    =   [
            'headers' => [
            'Content-Type' => 'application/json',
              'Authorization' => 'Bearer ' .$bearerToken,
            ],
            'http_errors' => false,
        ];
        return $headers;
    }

public static function GetDataByEndPoint($endPoint)
{

    $baseApiUrl = EndPoints::$BASE_URL;
        $url = $baseApiUrl . $endPoint;
    $client = new \GuzzleHttp\Client(self::getHttpHeaders());
    $response = $client->get($url, ['verify' => false]);

    $resp['statusCode'] = $response->getStatusCode();
    $resp['bodyContents'] = $response->getBody()->getContents();
    return $resp;
}
Enter fullscreen mode Exit fullscreen mode

In the above code snippet, I have a static method getHttpHeaders() from which I configure and return Http request headers which I pass to the Guzzle Http Client when making requests to the API. Setting the option 'http_errors' to false, disables Http Exceptions so that you can access status code on the response from the API.

GetDataByEndPoint is a static method which takes in an endpoint as a parameter from which to fetch data. With in the body of the method, I use a static variable $BASE_URL which is the api url from my custom class named EndPoints on which I concatenate the endpoint.

I create an instance of GuzzleHttp Client $client. The url is then passed to the get method on the $client instance to return response from the api. getContents() on getBody() is used to return contents from the api while getStatusCode() is used to return statusCode on the response object.

POST METHOD

public static function PostDataByEndPoint($endPoint, $body)
{
    $baseApiUrl = EndPoints::$BASE_URL;
        $url = $baseApiUrl . $endPoint;
    $client = new \GuzzleHttp\Client(self::getHttpHeaders());
    $request = $client->request('POST',$url, ['form_params' => 
         $body]);
    $response = $request->getBody()->getContents();
    return $response;
}
Enter fullscreen mode Exit fullscreen mode

In the method PostDataByEndPoint above, the difference from the get method is that I pass body or data which can be an array or json.

NOTE: You can also use ['body'=> json_encode($body)] instead of ['form_params' => $body] basing on your api input needs.

PUT METHOD

public static function PutDataByEndPoint($endPoint, $body)
{
    $baseApiUrl = EndPoints::$BASE_URL;
        $url = $baseApiUrl . $endPoint;
    $client = new \GuzzleHttp\Client(self::getHttpHeaders());
    $request = $client->request('PUT',$url, ['form_params' => $body]);
    $response = $request->getBody()->getContents();
    return $response;
}
Enter fullscreen mode Exit fullscreen mode

In PutDataByEndPoint method, I pass the endpoint and body of data as well just like in the post method above.

DELETE METHOD

 public static function deleteDataByEndPoint($endPoint, $body){
    $baseApiUrl = EndPoints::$BASE_URL;
         $url = $baseApiUrl . $endPoint;
    $client = new \GuzzleHttp\Client(self::getHttpHeaders());
    $request = $client->delete($url, ['body' => 
        json_encode($body)]);
    $response = $request->getBody()->getContents();
    return $response;

}
Enter fullscreen mode Exit fullscreen mode

The above method deleteDataByEndPoint, it takes in an endpoint and then body(can be an array containing id that will uniquely identify a record to be deleted from the data source).

NOTE: All the methods above can be used anywhere in any of your controllers or classes meaning that they are reusable.

Usage of the get method GetDataByEndPoint

  $endPoint = '/users';
  $resp = ApiRequestResponse::GetDataByEndPoint($endPoint);
  $apiResult = json_decode($resp, true);
  $data = $apiResult['data'];
Enter fullscreen mode Exit fullscreen mode

Usage of the post method PostDataByEndPoint

 $reqParams = array('first_name' => $first_name,
                    'last_name' => $last_name,
                    'address' => $address,
                    'age' => $age,
             );

$endPoint = '/users';
$resp = ApiRequestResponse::PostDataByEndPoint($endPoint, $reqParams);
$apiResult = json_decode($resp, true);
$statusCode = $apiResult['statusCode'];
$message = $apiResult['message'];
Enter fullscreen mode Exit fullscreen mode

Usage of the put method PutDataByEndPoint

 $reqParams = array('id' => $id,
                    'first_name' => $first_name,
                    'last_name' => $last_name,
                    'address' => $address,
                    'age' => $age,
             );
$endPoint = '/users';
$resp = ApiRequestResponse::PutDataByEndPoint($endPoint, $reqParams);
$apiResult = json_decode($resp, true);
$statusCode = $apiResult['statusCode'];
$message = $apiResult['message'];
Enter fullscreen mode Exit fullscreen mode

Usage of the delete method deleteDataByEndPoint

$reqParams = array('id' => $id,
                    'user' => $request->user()->name,
             );
$endPoint = '/users';
$resp=ApiRequestResponse::deleteDataByEndPoint($endPoint, $reqParams);
$apiResult = json_decode($resp, true);
$statusCode =$apiResult['statusCode'];
$message =$apiResult['message'];
Enter fullscreen mode Exit fullscreen mode

EndPoints class

<?php
namespace App\Helpers;
class EndPoints {
public static $BASE_URL = 'placehereyourapibaseurl'; // API URL
}
Enter fullscreen mode Exit fullscreen mode

NOTES:
1.The methods GetDataByEndPoint, PostDataByEndPoint, PutDataByEndPoint, deleteDataByEndPoint can be given names of your choice and ApiRequestResponse is the class that contains these methods.
2. If you want to pass full urls instead of the endpoints, you can go ahead and do that. That means that you forego using EndPoints class to get API url. But remember using EndPoints class helps you to configure your api url at once. The other approach of passing full urls means that you have to edit it everywhere in your classes whenever the api url changes which is not a good practice.

That's the end of today's tutorial, hope it helps you!
You can leave comment basing on how you have seen this post. Thank you.

Top comments (0)