PHP HTTP Request With Guzzle


 PHP HTTP Request With Guzzle  
 

If you are consuming some kind of API with complex PHP HTTP requests which doesn’t provide a clean wrapper library, I can feel the nightmare you might be having. Same could be happen if you are yourself writing such kind of API wrapper as well. Here, I will try to introduce you with guzzle library and getting a quick start. This article is targeted for complete beginners, so if you are already somewhat experienced, you either might skip this or review it and help me improve it to fit as a robust getting started tutorial.

What Is Guzzle?

Being there a lot of complexity in cURL support in PHP, there is a great community of PHP developers and their valuable contributions, which causes for an excellent and stable library, Guzzle to be released. It’s a lot helpful to create, customize, process complex HTTP requests/responses(such as token based authentication etc) easily and efficiently. As a result, even many complex API providers, such as AWS PHP SDK utilizes this library as the PHP http request processing layer.

What Can Be Done With Guzzle?

You will might be interested to know why we are talking about this and what we actually can do with it. Well, there are several use cases for this and one or more could be yours:

  • Consume Third Party API/Authentication: Whether you are implementing a facebook based authentication or showing some data which are fed from third-party web services, this is the tool you will want as your primary client to do such kind of jobs.
  • Scraping WebSite Data: If you are about to work on any web scraping related tasks, either create a crawler or collect and parse various kind of data content, this library is going to do wonder for you.
  • Easier: If you are trying to do this with raw support from php, in case of a little complex API consumption, you will fall into a sea of code, which will be harder to maintain/debug. This library can act as a nice layer over PHP cURL so that you can concentrate on the main parts.
  • Performance: For simple data retrieval, its possible to do with file_get_contents
  • function that might seem easier for you. But, in terms of performance, cURL still should be your primary choice. So, instead of digging into complexity of cURL library, this library will give you easy to understand API interface. Also, with guzzle, you will able to take the full power of curl to perform multiple parallel requests simultaneously as I described on my another article about retrieving multiple objects from AWS S3 in parallel.

It is known one of the best HTTP client available in PHP language, which also acts as a complete framework to build custom web service clients.

Alternative Of Guzzle For PHP HTTP Request:

I guess, symfony httpfoundation along with httpkernel components together can act in similar way, which might good alternative of this library. Codeception, The popular code coverage/acceptance testing framework, is built on these symfony components and works in similar way to fill-up web forms, post data, match response.

Download/Installation Guzzle:

You can easily download the complete source and integrate to your project manually from Guzzle github repo. On the other hand, if you are using composer in your application, then can use simple entry as dependency as below:

{
    "require": {
        "guzzlehttp/guzzle": "~4.0"
    }
}

Creating Your First Guzzle Based Request:

To create your very first request with guzzle, a code snippet as simple as below will work:

use GuzzleHttp\Client;
use GuzzleHttp\Message\Request;
use GuzzleHttp\Message\Response;

$client = new Client();
$response = $client->get("https://api.github.com/");
var_dump($response->json());

So, after executing the script, you should be able to see some output like below:

{
  "current_user_url": "https://api.github.com/user",
  "authorizations_url": "https://api.github.com/authorizations",
  "code_search_url": "https://api.github.com/search/code?q={query}{&page,per_page,sort,order}",
  "emails_url": "https://api.github.com/user/emails",
  .....................
}

Hola! You have just written the smallest tinny client to consume Github API! well, it’s not much, but as long as its working, it’s a sign to the great path of API consumption road. Congratulation!

Performing POST Request:

POST request is quite similar to the previous one, just additionally you will have to feed data with it. An example is given below:

$client = new Client();
$response = $client->post("http://requestb.in/tg4brftg", [
    'headers' => ['X-Foo' => 'Bar'],
    'body'    => ['field_name' => 'value']
]);
var_dump($response->getStatusCode());

Also, to test your implementation whether its sending data properly, you can create an request bin to collect and show what you just sent.

There are of course all other kind of request types available put for PUT, delete for DELETE etc.

oAuth Based Authentication With Guzzle:

Well, guzzle decoupled the oAuth mechanism into a separate subscriber plugin with nice simple usage example. You can see how easy it is to create a twitter API client!

Anything Else?

You can see the list of currently available plugin with guzzle to match to your needs such as implement caching/logging etc. However, if you have any questions about basic understanding of this library or related to PHP HTTP request, you are welcome to leave a comment. Happy coding!

Comments

  1. Matt Robinson says

    Http-foundation is not an alternative to Guzzle, it’s an OO interface to fake or incoming requests. Alternatives to Guzzle include Requests and Buzz

Leave a Reply