How to Use Guzzle – A PHP HTTP Client for Sending HTTP Requests

The developer always comes across a task where they need to send HTTP requests to other resources and handle the response. The popular way to perform these tasks is by using a cURL. However, using the cURL is not relatively easy for a beginner. Also to write a script in cURL, your server should have enabled the cURL extension.

Guzzle is an alternative to cURL. It’s a PHP HTTP client that makes it easy to send HTTP requests and trivial to integrate with web services. Even, I can say from my experience Guzzle is better than cURL. It is simple and easy to use. If you are using Guzzle, you don’t need to have cURL extension on your server. It gives you better formatting of code compared to cURL.

That being said, let’s see how to use Guzzle in your application.

Installation

The recommended way to install Guzzle is through the Composer. If you have not installed Composer on your system, you can get it from here.

Composer

Open the terminal in your project root directory and run the below command to install Guzzle.

composer require guzzlehttp/guzzle

Guzzle provides support for all HTTP requests which are GET, DELETE, HEAD, OPTIONS, PATCH, POST and PUT. In this tutorial, we study how to use Guzzle for sending HTTP requests and handle responses with it.

As an example, I take REQ|RES service which provides a fake real API for testing HTTP requests.

How to Send HTTP Request Using Guzzle

Upon installation of the Guzzle library, you need to include a Guzzle environment in your file as follows.

<?php
require_once "vendor/autoload.php";

use GuzzleHttp\Client;

Now let’s try a few operations one by one like GET, POST, File upload, copy file from remote URL to a local directory, PUT, PATCH, and DELETE.

GET Request using Guzzle

If you look at the REQ|RES website, they provided a few endpoints for ‘GET’ requests. I will take the example of ‘LIST USERS’ endpoint. For getting users list, they ask to send a GET request to this endpoint https://reqres.in/api/users?page=2.

In Guzzle, we will send this GET request as follows.

<?php
require_once "vendor/autoload.php";
 
use GuzzleHttp\Client;

$client = new Client([
    // Base URI is used with relative requests
    'base_uri' => 'https://reqres.in',
]);
 
$response = $client->request('GET', '/api/users', [
    'query' => [
        'page' => '2',
    ]
]);

//get status code using $response->getStatusCode();

$body = $response->getBody();
$arr_body = json_decode($body);
print_r($arr_body);

First I extracted a ‘base_uri'(common URL) as https://reqres.in. Here, the final endpoint is ‘/api/users’ and it requires a GET parameter as ‘page’. In Guzzle, you can send GET parameters using the ‘query’ array as shown in the above code.

POST Request using Guzzle

Normally, there are 2 types of POST requests. You may need to POST parameters as ‘application/x-www-form-urlencoded’ POST request or upload JSON encoded data as a body of the request. You can post JSON encoded data as shown below.

<?php
require_once "vendor/autoload.php";
 
use GuzzleHttp\Client;

$client = new Client([
    // Base URI is used with relative requests
    'base_uri' => 'https://reqres.in',
]);

$response = $client->request('POST', '/api/users', [
    'json' => [
        'name' => 'Sam',
        'job' => 'Developer'
    ]
]);

//get status code using $response->getStatusCode();

$body = $response->getBody();
$arr_body = json_decode($body);
print_r($arr_body);

In the case of ‘application/x-www-form-urlencoded’ POST request, you can POST parameters as follows.

<?php
require_once "vendor/autoload.php";
 
use GuzzleHttp\Client;

$client = new Client([
    // Base URI is used with relative requests
    'base_uri' => 'BASE_URL_ENDPOINT',
]);

$client->request('POST', '/endpoint_here', [
   'form_params' => [
       'foo' => 'bar',
       'baz' => ['hi', 'there!']
   ]
]);

In some cases, API endpoints ask you to send Authorization token in each HTTP request. The user can send this token as headers in your Guzzle request.

<?php
$client->request('POST', '/endpoint_here', [
    "headers" => [
        "Authorization" => "Bearer TOKEN_VALUE"
    ],
    'form_params' => [
       'foo' => 'bar',
       'baz' => ['hi', 'there!']
    ]
]);

Copy File from Remote Server using Guzzle

If you are looking to copy a file from a remote server to your local directory then Guzzle will be a better option. Let’s say you want to copy this image at https://artisansweb.net/wp-content/uploads/2020/03/blog.jpg as ‘blog.jpg’ to your local directory. We will write the code for it as shown below.

<?php
require_once "vendor/autoload.php";
 
use GuzzleHttp\Client;

$fp = fopen('blog.jpg', 'wb');

$client = new \GuzzleHttp\Client();
$request = $client->get('https://artisansweb.net/wp-content/uploads/2020/03/blog.jpg', ['sink' => $fp]);

fclose($fp);

File upload using Guzzle

As we all know, for uploading files we need to set the body of the request to a ‘multipart/form-data’ form. The basic code in Guzzle for uploading files would be written as below.

<?php
require_once "vendor/autoload.php";
 
use GuzzleHttp\Client;

$client = new Client([
    // Base URI is used with relative requests
    'base_uri' => 'BASE_URL_HERE',
]);

$client->request('POST', '/endpoint_here', [
    'multipart' => [
        [
            'name'     => 'files', // name value requires by endpoint
            'contents' => fopen('/path/to/file', 'r'),
            'filename' => 'custom_image.jpg'
        ],
    ]
]);

To demonstrate the file uploading, I will take a live example of reSmush.it API which sends an optimized version of the image in response. You need to POST your image to their endpoint. The code for it using Guzzle as follows.

<?php
require_once "vendor/autoload.php";
 
use GuzzleHttp\Client;

try {
    $client = new Client([
        // Base URI is used with relative requests
        'base_uri' => 'http://api.resmush.it',
    ]);

    $response = $client->request('POST', "?qlty=92", [
        'multipart' => [
            [
                'name'     => 'files', // name value requires by endpoint
                'contents' => fopen(getcwd().'/blog.jpg', 'r'),
                'filename' => 'blog.jpg',
                'headers'  => array('Content-Type' => mime_content_type(getcwd().'/blog.jpg'))
            ]
        ]
    ]);

    if (200 == $response->getStatusCode()) {
        $response = $response->getBody();
        $arr_result = json_decode($response);
        print_r($arr_result);
    }
} catch (\Exception $e) {
    echo $e->getMessage();
}

PUT, PATCH and DELETE Request using Guzzle

The PUT and PATCH requests are used to update the resources. However, these 2 requests do it differently.

PUT overwrites the entire entity if it already exists, and creates a new resource if it doesn’t exist. If you want to update the name of a person, you need to send the entire resource when making a PUT request.

<?php
<?php
require_once "vendor/autoload.php";
 
use GuzzleHttp\Client;
 
$client = new Client([
    // Base URI is used with relative requests
    'base_uri' => 'https://reqres.in',
]);
 
$response = $client->request('PUT', '/api/users/2', [
    'json' => [
        'name' => 'Sam',
        'job' => 'Developer'
    ]
]);
 
//get status code using $response->getStatusCode();

$body = $response->getBody();
$arr_body = json_decode($body);
print_r($arr_body);

The PATCH request applies a partial update to the resource. It means you are only required to send the data that you want to update, and it won’t affect or change anything else. So if you want to update the name of a person, you will only be required to send the name parameter.

<?php
require_once "vendor/autoload.php";
 
use GuzzleHttp\Client;
 
$client = new Client([
    // Base URI is used with relative requests
    'base_uri' => 'https://reqres.in',
]);
 
$response = $client->request('PATCH', '/api/users/2', [
    'json' => [
        'name' => 'Sam',
    ]
]);
 
//get status code using $response->getStatusCode();

$body = $response->getBody();
$arr_body = json_decode($body);
print_r($arr_body);

A DELETE request is straight-forward. You just need to hit the endpoint as follows.

<?php
require_once "vendor/autoload.php";
 
use GuzzleHttp\Client;
 
$client = new Client([
    // Base URI is used with relative requests
    'base_uri' => 'https://reqres.in',
]);
 
$response = $client->request('DELETE', '/api/users/2');
 
echo $response->getStatusCode(); //should gives 204

I hope you got to know about Guzzle and the basics of how to use it. You may read more about Guzzle Request Options on their documentation. Please share your thoughts or suggestions in the comment section below.

Related Articles

If you liked this article, then please subscribe to our YouTube Channel for video tutorials.

5 thoughts on “How to Use Guzzle – A PHP HTTP Client for Sending HTTP Requests

    1. Please:

      $client = new GuzzleHttp\Client();
      $bodyReturn = $client->request(‘POST’, $urlbase.$url_card, [
      ‘headers’ => [
      ‘Authorization’ => ‘Bearer ‘. $pub_key
      ],
      ‘json’ => [
      ‘number’=> ‘4242424242424242’,
      ‘cvc’=> ‘789’,
      ‘exp_month’ => ’12’,
      ‘exp_year’=> ’29’,
      ‘card_holder’ => ‘Pedro Pérez’
      ]
      ])->getBody()->getContents();

      I get an http error 405. Thank you.

Leave a Reply

Your email address will not be published. Required fields are marked *