Make a POST Request from PHP With Guzzle
POSTrequests from PHP … and I’d do it completely differently today. So, in an attempt to overcome some of the past crimes of the Internet in general and PHP in particular: here’s how to make a POST request in PHP, today, in a PHP 7+ world (it probably works in PHP 5 too).
Guzzle is brilliant. If you make web requests with PHP, use Guzzle. Guzzle actually does a bunch of other things too but today we’re making a
Install Guzzle like this:
composer require guzzlehttp/guzzle
If you are not using Composer yet then I strongly recommend you give it a whirl. The project itself has excellent documentation and there are some excellent guides around such as this one from Scotch. Seriously, do it. This post can wait.
Once the package is installed then you will need this at the top of
Now we can write some code!
Make A POST Request
Using Guzzle, we create a client, then instruct the client to make requests.
For testing, we can send requests to the excellent httpbin.org, this is an endpoint that will return you some JSON telling you what you sent to it. The code needs to:
- create a client with the URL
- send a POST request to
- capture the response and output it (it’s pretty printed JSON, you could easily
json_decode()this if you wanted)
require "vendor/autoload.php"; $client = new \GuzzleHttp\Client(["base_uri" => "http://httpbin.org"]); $response = $client->post("/post"); echo $response->getBody();
There, we did it! I think this is simpler to write than the old-style Curl equivalents and crucially much easier to read than my second favourite approach which is to use PHP’s streams. Note that you can still pass a context option to Guzzle if you need to.
Send Form Data With Your Post Request
It’s pretty unlikely that you’d want to send a
POST request so while I’ve outlined the process, there’s some more detail to look at here.
Here’s an example with some form fields being sent as data – run this code and you’ll see that httpbin returns this in it’s “form” element.
require "vendor/autoload.php"; $client = new \GuzzleHttp\Client(["base_uri" => "http://httpbin.org"]); $options = [ 'form_params' => [ "fruit" => "apple" ] ]; $response = $client->post("/post", $options); echo $response->getBody();
This is for a simple form; there’s also a
multipart parameter if you need that.
Send JSON With Your Post Request
An increasingly common use case for sending HTTP requests is to call APIs – and for that you probably want to pass JSON. Here’s an example that does that:
require "vendor/autoload.php"; $client = new \GuzzleHttp\Client(["base_uri" => "http://httpbin.org"]); $options = [ 'json' => [ "fruit" => "apple" ] ]; $response = $client->post("/post", $options); echo $response->getBody();
Look very closely! All that changes is
json and Guzzle automagically sorts out headers and JSON encoding and everything for us. If you didn’t want the magic, then you can set the
headers to meet the requirements of the application.
HTTP Requests in the Wild
It’s good to keep up with the current best practice in the industry but this is absolutely NOT the only way to do this! Many APIs also provide an SDK, Frameworks have their own HTTP clients, and it’s very likely that quite a few of them use Guzzle under the hood anyway. Hopefully this showed you one option for a clean and modern way to handle HTTP requests from PHP … I’m off to update those old blog posts with a link to this one!
Pingback: POSTing JSON Data With PHP cURL | LornaJane
Pingback: Three Ways to Make a POST Request from PHP | LornaJane
Remember to use [code]guzzlehttp/guzzle[/code] and not [code]guzzle/guzzle[/code]. The latter is an abandoned old version of guzzle, but you might find a dependency on it in an older codebase.
Although there’s well known advice to ‘not mock what you don’t own’. I find myself quite often padding in a mock of guzzle to unit test code that connects to an external API, which generally seems to work very well for testing code like [code]$response = $client->post(“/post”);[/code]. And it’s so much easier than it was with the old guzzle where you had to first get a request object from the client and and then send it.
Personally I tend to use HTTPlug rather than Guzzle, because that way I can avoid binding to a specific implementation. In practice I tend to use the Guzzle driver for it most often, but if I’m building an API client that’s potentially going to be reused, I don’t know what will make sense as the driver in that context, so it’s safer to use HTTPlug and just specify that it must have a suitable driver, so whoever uses it can make their own choice about HTTP clients. That said, I’m not sure it would be worth choosing HTTPlug over Guzzle for something other than a reusable library.