DEV Community

Cover image for Building HTTP clients with Guzzle
Titas Gailius
Titas Gailius

Posted on

Building HTTP clients with Guzzle

Whenever you integrate some external service that exposes an HTTP API you'll end up writting a client to interact with that service.

There're many different ways to build these http clients although the 3 most common approaches I encountered are listed below.

1. Creating a client class that extends guzzle.
extends guzzle

2. Creating a client class that handles all the logic and calls guzzle.
extends guzzle

3. Creating a client class where all the logic is handled by guzzle middleware.
extends guzzle

Which one do you prefer? Do you have any alternatives? Discuss.

Top comments (6)

Collapse
 
clanic profile image
Claudiu

I prefer the first example. Of course, is tightly coupled by Guzzle, but you don't change the HTTP Client every day.

However, if you really want to be more general, you can use the second option with a little "upgrade": use a contract (interface) to represent the type hint into the constructor. Like you define the constructor now, the Github class is tightly coupled by Guzzle client (and you go back to the first example).

Collapse
 
titasgailius profile image
Titas Gailius

I don't mind coupling it to Guzzle either although I personally got really used with the last example because as your client might get more complicated (request logging, different authentication strategies, handling failed requests, refreshing tokens, etc.), it is pretty cool that you can extract all of that stuff to dedicated classes.

Collapse
 
dramentol profile image
David Ramentol • Edited

All of them are equally coupled to Guzzle: "use GuzzleHttp\Client;"

There's no way to not couple some bit of your code to Guzzle if you use Guzzle, is there?

Collapse
 
aleksikauppila profile image
Aleksi Kauppila

I'd prefer writing an own http client interface and an adapter to guzzle.

Collapse
 
titasgailius profile image
Titas Gailius • Edited

So you basically have an example 2/3 in mind but decoupling guzzle with http-plug, right?

Collapse
 
aleksikauppila profile image
Aleksi Kauppila

I re-read the post and realized you were talking about integration, heh. I'll extend my comment a bit. So yes, i would write an adapter for Guzzle. If i didn't have to write that integration myself and the case would be using a library like twitteroauth then adapter again with a TwitterApi interface or something.

In case of writing the integration myself i'd be still trying my best to make it irrelevant that i'm using guzzle or even a http client at all. After all, the client probably only cares about the data that the integration provides. This is pretty speculative as i haven't really gotten around to build any kind of meaningful abstraction over these kinds of integrations.