If you need to send data to an API or web service in PHP, you‘ll likely need to make HTTP requests. While you can use PHP‘s built-in cURL functions, a cleaner and more powerful option is the Guzzle HTTP client library. Guzzle provides an easy-to-use interface for making all kinds of HTTP requests, including POST requests with JSON data.
In this guide, you‘ll learn how to install Guzzle, make a basic POST request, send JSON data, parse the JSON response, handle errors, and explore some advanced options. By the end, you‘ll be able to confidently communicate with APIs and web services using Guzzle in your PHP applications. Let‘s get started!
What is Guzzle?
Guzzle is a popular PHP HTTP client library that makes it easy to send HTTP requests and work with the responses. It provides a simple interface for making requests with different HTTP methods like GET, POST, PUT, PATCH, DELETE, etc.
Some key features of Guzzle include:
• Supports sending requests with URL query string parameters, form data, JSON data, multipart files, cookies, authentication, proxies, and more
• Ability to send both synchronous and asynchronous requests
• Streams request and response bodies to conserve memory
• Provides a simple interface for handling exceptions and errors
• Integrates with web service clients like Amazon Web Services via plugins
Guzzle uses the PSR-7 interfaces for HTTP messages, allowing interoperability with other libraries. It requires PHP 7.2 or higher.
Installing Guzzle
Before you can use Guzzle, you‘ll need to install it in your project. The recommended way is via Composer, PHP‘s package manager.
If you don‘t already have Composer installed, you can download it from https://getcomposer.org/. Then create a composer.json
file in your project‘s root directory if you don‘t have one:
{
"require": {
"guzzlehttp/guzzle": "^7.0"
}
}
This tells Composer to install the latest 7.x version of the guzzlehttp/guzzle
package.
Next, run this command to install Guzzle:
composer install
Composer will download Guzzle and its dependencies and generate an autoloader. To use Guzzle in your code files, include this line:
require ‘vendor/autoload.php‘;
Now you‘re ready to start making requests with Guzzle!
Making a Basic POST Request
To make a POST request with Guzzle, first create a client:
use GuzzleHttp\Client;
$client = new Client();
The Client
constructor accepts an array of configuration options, but we‘ll use the defaults for now.
Next call the post
method on the client, passing the URL and an array of options:
$response = $client->post(‘https://example.com/api/endpoint‘, [
‘form_params‘ => [
‘field_1‘ => ‘abc‘,
‘field_2‘ => ‘123‘
]
]);
By default, Guzzle will send data via form_params
as URL-encoded form data in the body of the request. The response is a Psr\Http\Message\ResponseInterface
object.
To get the response body as a string, use:
$responseBody = $response->getBody()->getContents();
You can inspect the response headers using methods like getHeader()
, getHeaders()
, getStatusCode()
, etc.
Sending JSON Data
To send JSON data instead of URL-encoded data, use the json
option instead of form_params
:
$response = $client->post(‘https://example.com/api/endpoint‘, [
‘json‘ => [
‘field_1‘ => ‘abc‘,
‘field_2‘ => 123
]
]);
Guzzle will automatically set the Content-Type
header to application/json
and JSON-encode the data for you.
Handling the JSON Response
If the API sends back a JSON response, you can use the getBody()
method to get the JSON string, then parse it with json_decode()
:
$responseBody = $response->getBody();
$jsonData = json_decode($responseBody, true);
This will give you a PHP array representing the parsed JSON data. The second argument true
makes json_decode
return an associative array instead of an object.
Alternatively, you can use Guzzle‘s built-in json()
method:
$data = json_decode($response->getBody(), true);
Error Handling
By default, if the response has a 400 or 500 level status code, Guzzle will throw an exception. You can catch and handle exceptions like this:
try {
$response = $client->post(...);
} catch (\GuzzleHttp\Exception\ClientException $e) {
$response = $e->getResponse();
$errorMessage = json_decode($response->getBody(), true)[‘error‘];
}
The exception provides methods to access the request, response, and error message, so you can gracefully handle the error condition.
Advanced Options
Guzzle has many other options you can use to customize your requests. Here are a few common ones.
Authentication
To send a request with basic auth, use the auth
option:
$response = $client->post(‘https://example.com/api/endpoint‘, [
‘auth‘ => [‘username‘, ‘password‘]
]);
Proxies
To send a request through a proxy server, use the proxy
option:
$response = $client->post(‘https://example.com/api/endpoint‘, [
‘proxy‘ => ‘tcp://localhost:8125‘
]);
Timeout
To set a timeout for the request, use the timeout
option:
$response = $client->post(‘https://example.com/api/endpoint‘, [
‘timeout‘ => 10 // 10 second timeout
]);
Allow Redirects
By default, Guzzle will follow redirects. To disable this, use:
$response = $client->post(‘https://example.com/api/endpoint‘, [
‘allow_redirects‘ => false
]);
Cookies
To include cookies with the request, you can use the cookies
option with an instance of GuzzleHttp\Cookie\CookieJar
:
$jar = new \GuzzleHttp\Cookie\CookieJar();
$response = $client->post(‘https://example.com/api/endpoint‘, [
‘cookies‘ => $jar
]);
See the Guzzle Docs – Request Options for the full list of available options.
Example: Sending Data to an API
Here‘s a full example that sends JSON data to the JSONPlaceholder fake API:
use GuzzleHttp\Client;
$client = new Client();
$data = [
‘title‘ => ‘foo‘,
‘body‘ => ‘bar‘,
‘userId‘ => 1
];
try {
$response = $client->post(‘https://jsonplaceholder.typicode.com/posts‘, [
‘json‘ => $data
]);
$body = $response->getBody();
$responseData = json_decode($body, true);
print_r($responseData);
} catch (\GuzzleHttp\Exception\ClientException $e) {
$response = $e->getResponse();
$responseBodyAsString = json_decode($response->getBody()->getContents(), true);
print_r($responseBodyAsString);
}
This will send a POST request to create a new post, with the title
, body
, and userId
fields in the JSON body. It parses and outputs the JSON response data, handling any exceptions that occur.
Resources and Further Reading
Here are some resources to learn more about Guzzle:
• Guzzle Documentation
• Guzzle GitHub Repo
• Guzzle Tutorial – TopTal
• Asynchronous Requests with Guzzle
• Using Guzzle Middleware
Conclusion
Guzzle is a powerful tool for working with HTTP in PHP. Its clean interface makes it easy to compose requests, send data, parse responses, and handle errors. Whether you need to communicate with an external API or your own web service, Guzzle is up to the task.
In this guide, you learned how to install Guzzle, make a POST request with JSON data, handle the response, and use various options to customize the request. You also saw a full example of sending data to an API.
Armed with this knowledge, you can start integrating Guzzle into your PHP applications to level up your HTTP capabilities.
Happy requesting!