Using the Guzzle5 to access the web service in PHP

[Abstract]

Nowadays, we usually use the curl to access the web service in PHP. However, the curl does not have the useful features during accessing the web services. For example, set the timeout to restart requesting services, use the flexible parameters to build the url queries and so on.

In this article, you will learn how to use the Guzzle to make the HTTP request and access the web services in PHP. You will also learn some samples to access the mailing service and Image service.

[Introduction]

The Guzzle(https://github.com/guzzle/guzzle). It’s the PHP HTTP client and it’s on top of the PHP curl.It implements some missing features in PHP curl. You can see more details about the following link lists:

  1. The GitHub project: https://github.com/guzzle/guzzle
  2. The official documentation: http://docs.guzzlephp.org/en/stable/
  3. The Guzzle 5.3 documentation: http://docs.guzzlephp.org/en/5.3

[Prerequisite]

  • PHP Requirements: PHP 5.4+
  • To use the PHP stream handler, allow_url_fopen must be enabled in your system’s php.ini. allow_url_fopen.
  • To use the cURL handler, you must have a recent version of cURL >= 7.16.2 compiled with OpenSSL and zlib. cURL.

[Installation]

In this article, we introduce how to install the Guzzle5.3 via Composer(http://getcomposer.org/) and the steps are as follows:

  1. Download the composer.phar from the follwoing command:
    curl -sS https://getcomposer.org/installer | php
    

    Or you can download the latest composer.phar manually and check out the download section in this link: https://getcomposer.org/download.

  2. We create a project named guzzle-demo and create a composer.json in project root folder. Add the required Guzzle version in composer.json.The contents are as follows:
    {
       "require": {
           "guzzlehttp/guzzle":"5.*.*"
       }
    }
    

[Access the 3rd party web services]

In this article, we present some samples to access the MailGun and Imgur API via the Guzzle 5.

[MailGun]

MailGun is a mailing service which help us to be convenient to send the e-mail. And it also helps us to be flexible for sending e-mails.web present the curl and Guzzle5 sample code of sending e-mail are as follows:

CURL:


function send_simple_message() {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    curl_setopt($ch, CURLOPT_USERPWD, 'api:key-your-key');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
    curl_setopt($ch, CURLOPT_URL, 'https://api.mailgun.net/v3/your-domain.mailgun.org/messages');
    curl_setopt($ch, CURLOPT_POSTFIELDS, array('from' => 'peter <peter279k@gmail.com>',
           'to' => 'peter <peter279k@gmail.com>',
           'subject' => 'Hello', 'text' => 'Hello World'));
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

Guzzle5:

require "vendor/autoload.php";

$client = new GuzzleHttp\Client([
    'defaults' => [
    'auth' => ['api', 'key-your-api-key'],
    ]
]);

$res = $client->post('https://api.mailgun.net/v3/your-domain.mailgun.org/messages', [
    'body'=>[
        'from' => 'peter <peter279k@gmail.com>',
        'to' => 'peter <peter279k@gmail.com>',
        'subject' => 'Hello',
        'text' => 'Hello World'
    ]
]);
var_dump($res->json());

We can notice that the CURL is more completed than the Guzzle5 because the most of options are setted by Guzzle5. We will foucus on the parameters for the requesting queries.

[Imgur]

The Imgur is the famous Image service. It provides the Good space to store the own images. The sample code which is about the uploading image via CURL and Guzzle5 are as follows:

CURL:


$client_id = "your-imgur-client-id";
$image = file_get_contents("/path/to/image.png");

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.imgur.com/3/image.json');
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Client-ID ' . $client_id));
curl_setopt($ch, CURLOPT_POSTFIELDS, array('image' => base64_encode($image)));

$reply = curl_exec($ch);
curl_close($ch);

$reply = json_decode($reply, true);

var_dump($reply);

Guzzle5:


$imageFile = file_get_contents("../imgur_result.png");

$client = new GuzzleHttp\Client([
    'defaults' => [
        'headers' => ['Authorization' => 'Client-ID 3aa5c24753e1656'],
    ]
]);

$res = $client->post('https://api.imgur.com/3/image.json', [
    'body'=>[
        'image' => base64_encode($imageFile)
    ]
]);

var_dump($res->json());

[Summary]

In this tutorial, we present the steps to let you learn how to use the Guzzle5 to access the web services.If you get the certification error during the HTTP request, you should fix the certification bundle error by yourself.

We also present the sample code to make you compare the difference of using CURL and Guzzle5.We hope the readers can replace the Guzzle with CURL for the next web application project.And using the Guzzle to access the web service easily.

[References]

  1. MailGun user manual: https://documentation.mailgun.com/en/latest/user_manual.html
  2. Imgur API documentation: https://apidocs.imgur.com

 

 

Posted in PHP