Quickstart

This page provides a quick introduction to Guzzle and introductory examples. If you have not already installed, Guzzle, head over to the Installation page.

Make a Request

You can send requests with Guzzle using a GuzzleHttp\ClientInterface object.

Creating a Client

The procedural API is simple but not very testable; it’s best left for quick prototyping. If you want to use Guzzle in a more flexible and testable way, then you’ll need to use a GuzzleHttp\ClientInterface object.

  1. use GuzzleHttp\Client;
  2. $client = new Client();
  3. $response = $client->get('http://httpbin.org/get');
  4. // You can use the same methods you saw in the procedural API
  5. $response = $client->delete('http://httpbin.org/delete');
  6. $response = $client->head('http://httpbin.org/get');
  7. $response = $client->options('http://httpbin.org/get');
  8. $response = $client->patch('http://httpbin.org/patch');
  9. $response = $client->post('http://httpbin.org/post');
  10. $response = $client->put('http://httpbin.org/put');

You can create a request with a client and then send the request with the client when you’re ready.

  1. $request = $client->createRequest('GET', 'http://www.foo.com');
  2. $response = $client->send($request);

Client objects provide a great deal of flexibility in how request are transferred including default request options, subscribers that are attached to each request, and a base URL that allows you to send requests with relative URLs. You can find out all about clients in the Clients page of the documentation.

Using Responses

In the previous examples, we retrieved a $response variable. This value is actually a GuzzleHttp\Message\ResponseInterface object and contains lots of helpful information.

You can get the status code and reason phrase of the response.

  1. $code = $response->getStatusCode();
  2. // 200
  3. $reason = $response->getReasonPhrase();
  4. // OK

By providing the future request option to a request, you can send requests asynchronously using the promise interface of a future response.

  1. $client->get('http://httpbin.org', ['future' => true])
  2. ->then(function ($response) {
  3. echo $response->getStatusCode();
  4. });

Response Body

The body of a response can be retrieved and cast to a string.

  1. $body = $response->getBody();
  2. echo $body;
  3. // { "some_json_data" ...}

You can also read read bytes from body of a response like a stream.

  1. $body = $response->getBody();
  2. while (!$body->eof()) {
  3. echo $body->read(1024);
  4. }

JSON Responses

You can more easily work with JSON responses using the json() method of a response.

  1. $response = $client->get('http://httpbin.org/get');
  2. $json = $response->json();
  3. var_dump($json[0]['origin']);

Guzzle internally uses PHP’s json_decode() function to parse responses. If Guzzle is unable to parse the JSON response body, then a GuzzleHttp\Exception\ParseException is thrown.

XML Responses

You can use a response’s xml() method to more easily work with responses that contain XML data.

  1. $response = $client->get('https://github.com/mtdowling.atom');
  2. $xml = $response->xml();
  3. echo $xml->id;
  4. // tag:github.com,2008:/mtdowling

Guzzle internally uses a SimpleXMLElement object to parse responses. If Guzzle is unable to parse the XML response body, then a GuzzleHttp\Exception\ParseException is thrown.

Query String Parameters

Sending query string parameters with a request is easy. You can set query string parameters in the request’s URL.

  1. $response = $client->get('http://httpbin.org?foo=bar');

You can also specify the query string parameters using the query request option.

  1. $client->get('http://httpbin.org', [
  2. 'query' => ['foo' => 'bar']
  3. ]);

And finally, you can build up the query string of a request as needed by calling the getQuery() method of a request and modifying the request’s GuzzleHttp\Query object as needed.

  1. $request = $client->createRequest('GET', 'http://httpbin.org');
  2. $query = $request->getQuery();
  3. $query->set('foo', 'bar');
  4. // You can use the query string object like an array
  5. $query['baz'] = 'bam';
  6. // The query object can be cast to a string
  7. echo $query;
  8. // foo=bar&baz=bam
  9. // Setting a value to false or null will cause the "=" sign to be omitted
  10. $query['empty'] = null;
  11. echo $query;
  12. // foo=bar&baz=bam&empty
  13. // Use an empty string to include the "=" sign with an empty value
  14. $query['empty'] = '';
  15. echo $query;
  16. // foo=bar&baz=bam&empty=

Request and Response Headers

You can specify request headers when sending or creating requests with a client. In the following example, we send the X-Foo-Header with a value of value by setting the headers request option.

  1. $response = $client->get('http://httpbin.org/get', [
  2. 'headers' => ['X-Foo-Header' => 'value']
  3. ]);

You can view the headers of a response using header specific methods of a response class. Headers work exactly the same way for request and response object.

You can retrieve a header from a request or response using the getHeader() method of the object. This method is case-insensitive and by default will return a string containing the header field value.

  1. $response = $client->get('http://www.yahoo.com');
  2. $length = $response->getHeader('Content-Length');

Header fields that contain multiple values can be retrieved as a string or as an array. Retrieving the field values as a string will naively concatenate all of the header values together with a comma. Because not all header fields should be represented this way (e.g., Set-Cookie), you can pass an optional flag to the getHeader() method to retrieve the header values as an array.

  1. $values = $response->getHeader('Set-Cookie', true);
  2. foreach ($values as $value) {
  3. echo $value;
  4. }

You can test if a request or response has a specific header using the hasHeader() method. This method accepts a case-insensitive string and returns true if the header is present or false if it is not.

You can retrieve all of the headers of a message using the getHeaders() method of a request or response. The return value is an associative array where the keys represent the header name as it will be sent over the wire, and each value is an array of strings associated with the header.

  1. $headers = $response->getHeaders();
  2. foreach ($message->getHeaders() as $name => $values) {
  3. echo $name . ": " . implode(", ", $values);
  4. }

Modifying headers

The headers of a message can be modified using the setHeader(), addHeader(), setHeaders(), and removeHeader() methods of a request or response object.

  1. $request = $client->createRequest('GET', 'http://httpbin.org/get');
  2. // Set a single value for a header
  3. $request->setHeader('User-Agent', 'Testing!');
  4. // Set multiple values for a header in one call
  5. $request->setHeader('X-Foo', ['Baz', 'Bar']);
  6. // Add a header to the message
  7. $request->addHeader('X-Foo', 'Bam');
  8. echo $request->getHeader('X-Foo');
  9. // Baz, Bar, Bam
  10. // Remove a specific header using a case-insensitive name
  11. $request->removeHeader('x-foo');
  12. echo $request->getHeader('X-Foo');
  13. // Echoes an empty string: ''

Uploading Data

Guzzle provides several methods of uploading data.

You can send requests that contain a stream of data by passing a string, resource returned from fopen, or a GuzzleHttp\Stream\StreamInterface object to the body request option.

  1. $r = $client->post('http://httpbin.org/post', ['body' => 'raw data']);

You can easily upload JSON data using the json request option.

  1. $r = $client->put('http://httpbin.org/put', ['json' => ['foo' => 'bar']]);

POST Requests

In addition to specifying the raw data of a request using the body request option, Guzzle provides helpful abstractions over sending POST data.

Sending POST Fields

Sending application/x-www-form-urlencoded POST requests requires that you specify the body of a POST request as an array.

  1. $response = $client->post('http://httpbin.org/post', [
  2. 'body' => [
  3. 'field_name' => 'abc',
  4. 'other_field' => '123'
  5. ]
  6. ]);

You can also build up POST requests before sending them.

  1. $request = $client->createRequest('POST', 'http://httpbin.org/post');
  2. $postBody = $request->getBody();
  3. // $postBody is an instance of GuzzleHttp\Post\PostBodyInterface
  4. $postBody->setField('foo', 'bar');
  5. echo $postBody->getField('foo');
  6. // 'bar'
  7. echo json_encode($postBody->getFields());
  8. // {"foo": "bar"}
  9. // Send the POST request
  10. $response = $client->send($request);

Sending POST Files

Sending multipart/form-data POST requests (POST requests that contain files) is the same as sending application/x-www-form-urlencoded, except some of the array values of the POST fields map to PHP fopen resources, or GuzzleHttp\Stream\StreamInterface, or GuzzleHttp\Post\PostFileInterface objects.

  1. use GuzzleHttp\Post\PostFile;
  2. $response = $client->post('http://httpbin.org/post', [
  3. 'body' => [
  4. 'field_name' => 'abc',
  5. 'file_filed' => fopen('/path/to/file', 'r'),
  6. 'other_file' => new PostFile('other_file', 'this is the content')
  7. ]
  8. ]);

Just like when sending POST fields, you can also build up POST requests with files before sending them.

  1. use GuzzleHttp\Post\PostFile;
  2. $request = $client->createRequest('POST', 'http://httpbin.org/post');
  3. $postBody = $request->getBody();
  4. $postBody->setField('foo', 'bar');
  5. $postBody->addFile(new PostFile('test', fopen('/path/to/file', 'r')));
  6. $response = $client->send($request);

Cookies

Guzzle can maintain a cookie session for you if instructed using the cookies request option.

  • Set to true to use a shared cookie session associated with the client.
  • Pass an associative array containing cookies to send in the request and start a new cookie session.
  • Set to a GuzzleHttp\Subscriber\CookieJar\CookieJarInterface object to use an existing cookie jar.

Redirects

Guzzle will automatically follow redirects unless you tell it not to. You can customize the redirect behavior using the allow_redirects request option.

  • Set to true to enable normal redirects with a maximum number of 5 redirects. This is the default setting.
  • Set to false to disable redirects.
  • Pass an associative array containing the ‘max’ key to specify the maximum number of redirects and optionally provide a ‘strict’ key value to specify whether or not to use strict RFC compliant redirects (meaning redirect POST requests with POST requests vs. doing what most browsers do which is redirect POST requests with GET requests).
  1. $response = $client->get('http://github.com');
  2. echo $response->getStatusCode();
  3. // 200
  4. echo $response->getEffectiveUrl();
  5. // 'https://github.com/'

The following example shows that redirects can be disabled.

  1. $response = $client->get('http://github.com', ['allow_redirects' => false]);
  2. echo $response->getStatusCode();
  3. // 301
  4. echo $response->getEffectiveUrl();
  5. // 'http://github.com/'

Exceptions

Guzzle throws exceptions for errors that occur during a transfer.

  • In the event of a networking error (connection timeout, DNS errors, etc.), a GuzzleHttp\Exception\RequestException is thrown. This exception extends from GuzzleHttp\Exception\TransferException. Catching this exception will catch any exception that can be thrown while transferring (non-parallel) requests.

    1. use GuzzleHttp\Exception\RequestException;
    2. try {
    3. $client->get('https://github.com/_abc_123_404');
    4. } catch (RequestException $e) {
    5. echo $e->getRequest();
    6. if ($e->hasResponse()) {
    7. echo $e->getResponse();
    8. }
    9. }
  • A GuzzleHttp\Exception\ClientException is thrown for 400 level errors if the exceptions request option is set to true. This exception extends from GuzzleHttp\Exception\BadResponseException and GuzzleHttp\Exception\BadResponseException extends from GuzzleHttp\Exception\RequestException.

    1. use GuzzleHttp\Exception\ClientException;
    2. try {
    3. $client->get('https://github.com/_abc_123_404');
    4. } catch (ClientException $e) {
    5. echo $e->getRequest();
    6. echo $e->getResponse();
    7. }
  • A GuzzleHttp\Exception\ServerException is thrown for 500 level errors if the exceptions request option is set to true. This exception extends from GuzzleHttp\Exception\BadResponseException.

  • A GuzzleHttp\Exception\TooManyRedirectsException is thrown when too many redirects are followed. This exception extends from GuzzleHttp\Exception\RequestException.

All of the above exceptions extend from GuzzleHttp\Exception\TransferException.