Send JSON requests and get JSON responses with Guzzle

tl;dr Guzzle is great package to send and receive JSON data from a RESTful web service.

Guzzle is powerful PHP HTTP client. It helps to send HTTP requests and work with the responses by provding a readable abstraction layer to the underlying HTTP transport.

The documentation is extensive and even provides a Quickstart.

I consistently look for the example code to send and receive JSON data from a RESTful webservice however. So here we go.

Install Guzzle with Composer:

composer require guzzlehttp/guzzle

Send a synchronous request:

require __DIR__ . '/vendor/autoload.php';

$ping = (new \GuzzleHttp\Client())->get('');

Most webservices will require an access token to communicate with the provided API. This may be set with a header value. In the example below it is called X-Access-Token.

Guzzle may automatically convert an array to JSON and set all required headers upon sending the request. It however provides no method to read a JSON response anymore. This is because Guzzle implements a PSR-7 response object. This means that the getBody method returns the response body, but to decode JSON data it needs to be cast to a string before.

The complete example to send and receive JSON data from a RESTful webservice:

$client = new \GuzzleHttp\Client();

$requestUrl = '';
$requestToken = 'jso6TtMOrvRithiqnwMUmIB11d3Uh53uYIsDlob4eS';

$requestBody = [
    'text' => 'Hello World',
    'icon' => '5687'

$response = $client->request(
        'headers' => [
            'X-Access-Token' => $requestToken,
        'json' => $requestBody, // sets required JSON headers automatically
         //'debug' => 1

$data = json_decode((string) $response->getBody(), true); // true = array instead of object

I've saved this snippet into a Gist as well. A newer version might exist over there.

Update: It is advisable to wrap the request in a try/catch block to intercept network errors or broken responses. I added this block to the Gist.

⌛ Warning! This post is old. The information may be outdated.

No comments on this notepad. If you would like to add something, then dont hesitate to contact me via E-Mail or Twitter.