5
This page provides a quick introduction to Guzzle and introductory examples.
6
If you have not already installed, Guzzle, head over to the :ref:`installation`
12
You can send requests with Guzzle in one of two ways: through the procedural
13
API or using a ``GuzzleHttp\ClientInterface`` object. Using the procedural API
14
is an easy way to send a quick HTTP request. Using a Client object provides
15
much more flexibility in how requests are transferred and allows you to more
16
easily test the client.
21
Here's an example of sending a ``POST`` request using the procedural API.
25
$response = GuzzleHttp\post('http://httpbin.org/post', [
26
'headers' => ['X-Foo' => 'Bar'],
27
'body' => ['field_name' => 'value']
30
You can send all kinds of HTTP requests with the procedural API. Just call
31
the function that maps to the HTTP method name.
35
$response = GuzzleHttp\head('http://httpbin.org/get');
36
$response = GuzzleHttp\post('http://httpbin.org/post');
37
$response = GuzzleHttp\put('http://httpbin.org/put');
38
$response = GuzzleHttp\delete('http://httpbin.org/delete');
39
$response = GuzzleHttp\options('http://httpbin.org/get');
44
The procedural API is simple but not very testable; it's best left for quick
45
prototyping. If you want to use Guzzle in a more flexible and testable way,
46
then you'll need to use a ``GuzzleHttp\ClientInterface`` object.
50
use GuzzleHttp\Client;
52
$client = new Client();
53
$response = $client->get('http://httpbin.org/get');
55
// You can use the same methods you saw in the procedural API
56
$response = $client->delete('http://httpbin.org/delete');
57
$response = $client->head('http://httpbin.org/get');
58
$response = $client->options('http://httpbin.org/get');
59
$response = $client->patch('http://httpbin.org/patch');
60
$response = $client->post('http://httpbin.org/post');
61
$response = $client->put('http://httpbin.org/put');
63
You can create a request with a client and then send the request with the
64
client when you're ready.
68
$request = $client->createRequest('GET', 'http://www.foo.com');
69
$response = $client->send($request);
71
Client objects provide a great deal of flexibility in how request are
72
transferred including default request options, subscribers that are attached
73
to each request, and a base URL that allows you to send requests with relative
74
URLs. You can find out all about clients in the :doc:`clients` page of the
80
In the previous examples, we retrieved a ``$response`` variable. This value is
81
actually a ``GuzzleHttp\Message\ResponseInterface`` object and contains lots
82
of helpful information.
84
You can get the status code and reason phrase of the response.
88
$code = $response->getStatusCode();
91
$reason = $response->getReasonPhrase();
97
The body of a response can be retrieved and cast to a string.
101
$body = $response->getBody();
103
// { "some_json_data" ...}
105
You can also read read bytes from body of a response like a stream.
109
$body = $response->getBody();
111
while (!$body->eof()) {
112
echo $body->read(1024);
118
You can more easily work with JSON responses using the ``json()`` method of a
123
$response = $client->get('http://httpbin.org/get');
124
$json = $response->json();
125
var_dump($json[0]['origin']);
127
Guzzle internally uses PHP's ``json_decode()`` function to parse responses. If
128
Guzzle is unable to parse the JSON response body, then a
129
``GuzzleHttp\Exception\ParseException`` is thrown.
134
You can use a response's ``xml()`` method to more easily work with responses
135
that contain XML data.
139
$response = $client->get('https://github.com/mtdowling.atom');
140
$xml = $response->xml();
142
// tag:github.com,2008:/mtdowling
144
Guzzle internally uses a ``SimpleXMLElement`` object to parse responses. If
145
Guzzle is unable to parse the XML response body, then a
146
``GuzzleHttp\Exception\ParseException`` is thrown.
148
Query String Parameters
149
=======================
151
Sending query string parameters with a request is easy. You can set query
152
string parameters in the request's URL.
156
$response = $client->get('http://httpbin.org?foo=bar');
158
You can also specify the query string parameters using the ``query`` request
163
$client->get('http://httpbin.org', [
164
'query' => ['foo' => 'bar']
167
And finally, you can build up the query string of a request as needed by
168
calling the ``getQuery()`` method of a request and modifying the request's
169
``GuzzleHttp\Query`` object as needed.
173
$request = $client->createRequest('GET', 'http://httpbin.org');
174
$query = $request->getQuery();
175
$query->set('foo', 'bar');
177
// You can use the query string object like an array
178
$query['baz'] = 'bam';
180
// The query object can be cast to a string
184
// Setting a value to false or null will cause the "=" sign to be omitted
185
$query['empty'] = null;
187
// foo=bar&baz=bam&empty
189
// Use an empty string to include the "=" sign with an empty value
190
$query['empty'] = '';
192
// foo=bar&baz=bam&empty=
196
Request and Response Headers
197
----------------------------
199
You can specify request headers when sending or creating requests with a
200
client. In the following example, we send the ``X-Foo-Header`` with a value of
201
``value`` by setting the ``headers`` request option.
205
$response = $client->get('http://httpbin.org/get', [
206
'headers' => ['X-Foo-Header' => 'value']
209
You can view the headers of a response using header specific methods of a
210
response class. Headers work exactly the same way for request and response
213
You can retrieve a header from a request or response using the ``getHeader()``
214
method of the object. This method is case-insensitive and by default will
215
return a string containing the header field value.
219
$response = $client->get('http://www.yahoo.com');
220
$length = $response->getHeader('Content-Length');
222
Header fields that contain multiple values can be retrieved as a string or as
223
an array. Retrieving the field values as a string will naively concatenate all
224
of the header values together with a comma. Because not all header fields
225
should be represented this way (e.g., ``Set-Cookie``), you can pass an optional
226
flag to the ``getHeader()`` method to retrieve the header values as an array.
230
$values = $response->getHeader('Set-Cookie', true);
231
foreach ($values as $value) {
235
You can test if a request or response has a specific header using the
236
``hasHeader()`` method. This method accepts a case-insensitive string and
237
returns true if the header is present or false if it is not.
239
You can retrieve all of the headers of a message using the ``getHeaders()``
240
method of a request or response. The return value is an associative array where
241
the keys represent the header name as it will be sent over the wire, and each
242
value is an array of strings associated with the header.
246
$headers = $response->getHeaders();
247
foreach ($message->getHeaders() as $name => $values) {
248
echo $name . ": " . implode(", ", $values);
254
The headers of a message can be modified using the ``setHeader()``,
255
``addHeader()``, ``setHeaders()``, and ``removeHeader()`` methods of a request
260
$request = $client->createRequest('GET', 'http://httpbin.org/get');
262
// Set a single value for a header
263
$request->setHeader('User-Agent', 'Testing!');
265
// Set multiple values for a header in one call
266
$request->setHeader('X-Foo', ['Baz', 'Bar']);
268
// Add a header to the message
269
$request->addHeader('X-Foo', 'Bam');
271
echo $request->getHeader('X-Foo');
274
// Remove a specific header using a case-insensitive name
275
$request->removeHeader('x-foo');
276
echo $request->getHeader('X-Foo');
277
// Echoes an empty string: ''
282
Guzzle provides several methods of uploading data.
284
You can send requests that contain a stream of data by passing a string,
285
resource returned from ``fopen``, or a ``GuzzleHttp\Stream\StreamInterface``
286
object to the ``body`` request option.
290
$r = $client->post('http://httpbin.org/post', ['body' => 'raw data']);
292
You can easily upload JSON data using the ``json`` request option.
296
$r = $client->put('http://httpbin.org/put', ['json' => ['foo' => 'bar']]);
301
In addition to specifying the raw data of a request using the ``body`` request
302
option, Guzzle provides helpful abstractions over sending POST data.
307
Sending ``application/x-www-form-urlencoded`` POST requests requires that you
308
specify the body of a POST request as an array.
312
$response = $client->post('http://httpbin.org/post', [
314
'field_name' => 'abc',
315
'other_field' => '123'
319
You can also build up POST requests before sending them.
323
$request = $client->createRequest('POST', 'http://httpbin.org/post');
324
$postBody = $request->getBody();
326
// $postBody is an instance of GuzzleHttp\Post\PostBodyInterface
327
$postBody->setField('foo', 'bar');
328
echo $postBody->getField('foo');
331
echo json_encode($postBody->getFields());
334
// Send the POST request
335
$response = $client->send($request);
340
Sending ``multipart/form-data`` POST requests (POST requests that contain
341
files) is the same as sending ``application/x-www-form-urlencoded``, except
342
some of the array values of the POST fields map to PHP ``fopen`` resources, or
343
``GuzzleHttp\Stream\StreamInterface``, or
344
``GuzzleHttp\Post\PostFileInterface`` objects.
348
use GuzzleHttp\Post\PostFile;
350
$response = $client->post('http://httpbin.org/post', [
352
'field_name' => 'abc',
353
'file_filed' => fopen('/path/to/file', 'r'),
354
'other_file' => new PostFile('other_file', 'this is the content')
358
Just like when sending POST fields, you can also build up POST requests with
359
files before sending them.
363
use GuzzleHttp\Post\PostFile;
365
$request = $client->createRequest('POST', 'http://httpbin.org/post');
366
$postBody = $request->getBody();
367
$postBody->setField('foo', 'bar');
368
$postBody->addFile(new PostFile('test', fopen('/path/to/file', 'r')));
369
$response = $client->send($request);
374
Guzzle can maintain a cookie session for you if instructed using the
375
``cookies`` request option.
377
- Set to ``true`` to use a shared cookie session associated with the client.
378
- Pass an associative array containing cookies to send in the request and start
379
a new cookie session.
380
- Set to a ``GuzzleHttp\Subscriber\CookieJar\CookieJarInterface`` object to use
381
an existing cookie jar.
386
Guzzle will automatically follow redirects unless you tell it not to. You can
387
customize the redirect behavior using the ``allow_redirects`` request option.
389
- Set to true to enable normal redirects with a maximum number of 5 redirects.
390
This is the default setting.
391
- Set to false to disable redirects.
392
- Pass an associative array containing the 'max' key to specify the maximum
393
number of redirects and optionally provide a 'strict' key value to specify
394
whether or not to use strict RFC compliant redirects (meaning redirect POST
395
requests with POST requests vs. doing what most browsers do which is
396
redirect POST requests with GET requests).
400
$response = $client->get('http://github.com');
401
echo $response->getStatusCode();
403
echo $response->getEffectiveUrl();
404
// 'https://github.com/'
406
The following example shows that redirects can be disabled.
410
$response = $client->get('http://github.com', ['allow_redirects' => false]);
411
echo $response->getStatusCode();
413
echo $response->getEffectiveUrl();
414
// 'http://github.com/'
419
Guzzle throws exceptions for errors that occur during a transfer.
421
- In the event of a networking error (connection timeout, DNS errors, etc.),
422
a ``GuzzleHttp\Exception\RequestException`` is thrown. This exception
423
extends from ``GuzzleHttp\Exception\TransferException``. Catching this
424
exception will catch any exception that can be thrown while transferring
425
(non-parallel) requests.
429
use GuzzleHttp\Exception\RequestException;
432
$client->get('https://github.com/_abc_123_404');
433
} catch (RequestException $e) {
434
echo $e->getRequest();
435
if ($e->hasResponse()) {
436
echo $e->getResponse();
440
- A ``GuzzleHttp\Exception\ClientException`` is thrown for 400
441
level errors if the ``exceptions`` request option is set to true. This
442
exception extends from ``GuzzleHttp\Exception\BadResponseException`` and
443
``GuzzleHttp\Exception\BadResponseException`` extends from
444
``GuzzleHttp\Exception\RequestException``.
448
use GuzzleHttp\Exception\ClientException;
451
$client->get('https://github.com/_abc_123_404');
452
} catch (ClientException $e) {
453
echo $e->getRequest();
454
echo $e->getResponse();
457
- A ``GuzzleHttp\Exception\ServerException`` is thrown for 500 level
458
errors if the ``exceptions`` request option is set to true. This
459
exception extends from ``GuzzleHttp\Exception\BadResponseException``.
460
- A ``GuzzleHttp\Exception\TooManyRedirectsException`` is thrown when too
461
many redirects are followed. This exception extends from ``GuzzleHttp\Exception\RequestException``.
462
- A ``GuzzleHttp\Exception\AdapterException`` is thrown when an error occurs
463
in an HTTP adapter during a parallel request. This exception is only thrown
464
when using the ``sendAll()`` method of a client.
466
All of the above exceptions extend from
467
``GuzzleHttp\Exception\TransferException``.