PHP - Why Use Guzzle Instead of cURL?

Cato Minor picture Cato Minor · Apr 11, 2016 · Viewed 32.2k times · Source

In my application, I originally began using cURL to retrieve data from various APIs. Today, I tried using Guzzle to complete the same task. So far, both cURL and Guzzle seem to work equally good.

Judging by Github, a lot of people seem to like Guzzle, but I don't really appreciate why.

My question:

For my situation (retrieving data from various APIs), is it preferable to use Guzzle? Will I eventually come to regret it, if I use cURL instead Guzzle (or vice versa)?

I am using PHP / Laravel.

Answer

Fabio Antunes picture Fabio Antunes · Apr 11, 2016

Why use Guzzle?

First of all Guzzle is an abstraction layer for http request, although it uses cURL by default you can use any other http client that you want:

Does Guzzle require cURL?

No. Guzzle can use any HTTP handler to send requests. This means that Guzzle can be used with cURL, PHP's stream wrapper, sockets, and non-blocking libraries like React. You just need to configure an HTTP handler to use a different method of sending requests

Note: Guzzle has historically only utilized cURL to send HTTP requests. cURL is an amazing HTTP client (arguably the best), and Guzzle will continue to use it by default when it is available. It is rare, but some developers don't have cURL installed on their systems or run into version specific issues. By allowing swappable HTTP handlers, Guzzle is now much more customizable and able to adapt to fit the needs of more developers.

Since you are using Laravel, if by any chances you use any email API then by now you already have Guzzle installed. On your Laravel's composer.json you can see a suggestion:

"suggest": {
    ...
    "guzzlehttp/guzzle": "Required to use the Mailgun and Mandrill mail drivers and the ping methods on schedules (~5.3|~6.0).",
    ...
}

Another reason will be reusing code, take a look at the comment made by bogdan the amount of code needed to do a simple http request with cURL. With Guzzle is way more simpler, cleaner, readable and reusable. Its quite easy to create a service that will encapsulate your Http requests.

Guzzle also allows you to do async requests, in a very similar way you do with javascript using promises.

Last but not least, tests! It's way more easier to do tests to your API or create Unit tests for your app and mock the http requests with Guzzle than using cURL. More info about the tests here

BUT if you only want to do only a couple of simple http requests (which doesn't seem to be the case) you don't care about tests and you don't want to have a dependency on Guzzle go for cURL.