
If you are consuming some kind of API with complex PHP HTTP requests which don’t provide a clean wrapper library, I can feel the nightmare you might be having. The same could happen if you are writing such kind of API wrapper as well. Here, I will try to introduce you to Guzzle library and get a quick start. This article is targeted at complete beginners, so if you are already somewhat experienced, you might either 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 caused an excellent and stable library, Guzzle, to be released. It’s a lot helpful to create, customize, and 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, utilize this library as the PHP HTTP request processing layer.
What Can Be Done With Guzzle?
You will be interested to know why we are talking about this and what we 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 kinds of data content, you can have this library do wonders 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 lovely 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
a function that might seem easier for you. But, in terms of performance, cURL still should be your primary choice. So, instead of digging into the complexity of the cURL library, this library will give you easy to understand of API interface. Also, with Guzzle, you will able to take the full power of curl to perform multiple parallel requests simultaneously, as I described in another article about retrieving multiple objects from AWS S3 in parallel.
It is known as one of the best HTTP clients available in the PHP language as of now, which also acts as a complete framework to build custom web service clients.
Alternative Of Guzzle For PHP HTTP Request:
I guess Symfony HTTP foundation, along with HTTP kernel components together, can act in a similar way, which might be a good alternative to this library. Codeception, The popular code coverage/acceptance testing framework, is built on these Symfony components and works in a similar way to fill up web forms, post data, and match responses.
Download/Installation Guzzle:
You can easily download the complete source and integrate it into your project manually from Guzzle github repo. On the other hand, if you are using composer in your application, then you can use the simple entry as a dependency as below:
{
"require": {
"guzzlehttp/guzzle": "~4.0"
}
}
Code language: JSON / JSON with Comments (json)
Creating Your First Guzzle-Based Request:
To create your very first request with guzzle, a code snippet as simple as the one 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());
Code language: PHP (php)
So, after executing the script, you should be able to see some output like the 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",
.....................
}
Code language: JavaScript (javascript)
Hola! You have just written the smallest tinny client to consume Github API! well, it’s not much, but as long as it’s working, it’s a sign to the great path of the API consumption road. Congratulation!
Performing POST Request:
The POST request is quite similar to the previous one. Just add 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());
Code language: PHP (php)
Also, to test your implementation to see whether it’s sending data properly, you can create a request bin to collect and show what you just sent.
There are, of course, all other kinds 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 a 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 plugins with Guzzle to match your needs, such as implementing caching/logging etc. However, if you have any questions about the basic understanding of this library or related to PHP HTTP requests, you are welcome to leave a comment. Happy coding!
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
Not alone, but with use of http-kernel component(which provides a client) it seems to perform similar functionality, I guess(Though I haven’t use them in such way).
HttpFoundation + HttpKernel is not designed to create request, it’s for catch request. I’ll clearly not recommend it.