~canonical-sysadmins/wordpress/openstack-objectstorage-k8s

« back to all changes in this revision

Viewing changes to vendor/guzzlehttp/guzzle/docs/clients.rst

  • Committer: Jacek Nykis
  • Date: 2015-02-11 15:35:31 UTC
  • Revision ID: jacek.nykis@canonical.com-20150211153531-hmy6zi0ov2qfkl0b
Initial commit

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
=======
 
2
Clients
 
3
=======
 
4
 
 
5
Clients are used to create requests, create transactions, send requests
 
6
through an HTTP adapter, and return a response. You can add default request
 
7
options to a client that are applied to every request (e.g., default headers,
 
8
default query string parameters, etc.), and you can add event listeners and
 
9
subscribers to every request created by a client.
 
10
 
 
11
Creating a client
 
12
=================
 
13
 
 
14
The constructor of a client accepts an associative array of configuration
 
15
options.
 
16
 
 
17
base_url
 
18
    Configures a base URL for the client so that requests created
 
19
    using a relative URL are combined with the ``base_url`` of the client
 
20
    according to section `5.2 of RFC 3986 <http://tools.ietf.org/html/rfc3986#section-5.2>`_.
 
21
 
 
22
    .. code-block:: php
 
23
 
 
24
        // Create a client with a base URL
 
25
        $client = new GuzzleHttp\Client(['base_url' => 'https://github.com']);
 
26
        // Send a request to https://github.com/notifications
 
27
        $response = $client->get('/notifications');
 
28
 
 
29
    `Absolute URLs <http://tools.ietf.org/html/rfc3986#section-4.3>`_ sent
 
30
    through a client will not use the base URL of the client.
 
31
 
 
32
adapter
 
33
    Configures the HTTP adapter (``GuzzleHttp\Adapter\AdapterInterface``) used
 
34
    to transfer the HTTP requests of a client. Guzzle will, by default, utilize
 
35
    a stacked adapter that chooses the best adapter to use based on the provided
 
36
    request options and based on the extensions available in the environment. If
 
37
    cURL is installed, it will be used as the default adapter. However, if a
 
38
    request has the ``stream`` request option, the PHP stream wrapper adapter
 
39
    will be used (assuming ``allow_url_fopen`` is enabled in your PHP
 
40
    environment).
 
41
 
 
42
parallel_adapter
 
43
    Just like the ``adapter`` option, you can choose to specify an adapter
 
44
    that is used to send requests in parallel
 
45
    (``GuzzleHttp\Adapter\ParallelAdapterInterface``). Guzzle will by default
 
46
    use cURL to send requests in parallel, but if cURL is not available it will
 
47
    use the PHP stream wrapper and simply send requests serially.
 
48
 
 
49
message_factory
 
50
    Specifies the factory used to create HTTP requests and responses
 
51
    (``GuzzleHttp\Message\MessageFactoryInterface``).
 
52
 
 
53
defaults
 
54
    Associative array of :ref:`request-options` that are applied to every
 
55
    request created by the client. This allows you to specify things like
 
56
    default headers (e.g., User-Agent), default query string parameters, SSL
 
57
    configurations, and any other supported request options.
 
58
 
 
59
emitter
 
60
    Specifies an event emitter (``GuzzleHttp\Event\EmitterInterface``) instance
 
61
    to be used by the client to emit request events. This option is useful if
 
62
    you need to inject an emitter with listeners/subscribers already attached.
 
63
 
 
64
Here's an example of creating a client with various options, including using
 
65
a mock adapter that just returns the result of a callable function and a
 
66
base URL that is a URI template with parameters.
 
67
 
 
68
.. code-block:: php
 
69
 
 
70
    use GuzzleHttp\Client;
 
71
 
 
72
    $client = new Client([
 
73
        'base_url' => ['https://api.twitter.com/{version}/', ['version' => 'v1.1']],
 
74
        'defaults' => [
 
75
            'headers' => ['Foo' => 'Bar'],
 
76
            'query'   => ['testing' => '123'],
 
77
            'auth'    => ['username', 'password'],
 
78
            'proxy'   => 'tcp://localhost:80'
 
79
        ]
 
80
    ]);
 
81
 
 
82
Sending Requests
 
83
================
 
84
 
 
85
Requests can be created using various methods of a client. You can create
 
86
**and** send requests using one of the following methods:
 
87
 
 
88
- ``GuzzleHttp\Client::get``: Sends a GET request.
 
89
- ``GuzzleHttp\Client::head``: Sends a HEAD request
 
90
- ``GuzzleHttp\Client::post``: Sends a POST request
 
91
- ``GuzzleHttp\Client::put``: Sends a PUT request
 
92
- ``GuzzleHttp\Client::delete``: Sends a DELETE request
 
93
- ``GuzzleHttp\Client::options``: Sends an OPTIONS request
 
94
 
 
95
Each of the above methods accepts a URL as the first argument and an optional
 
96
associative array of :ref:`request-options` as the second argument.
 
97
 
 
98
.. code-block:: php
 
99
 
 
100
    $client = new GuzzleHttp\Client();
 
101
 
 
102
    $client->put('http://httpbin.org', [
 
103
        'headers' => ['X-Foo' => 'Bar'],
 
104
        'body' => 'this is the body!',
 
105
        'save_to' => '/path/to/local/file',
 
106
        'allow_redirects' => false,
 
107
        'timeout' => 5
 
108
    ]);
 
109
 
 
110
Error Handling
 
111
--------------
 
112
 
 
113
When a recoverable error is encountered while calling the ``send()`` method of
 
114
a client, a ``GuzzleHttp\Exception\RequestException`` is thrown.
 
115
 
 
116
.. code-block:: php
 
117
 
 
118
    use GuzzleHttp\Client;
 
119
    use GuzzleHttp\Exception\RequestException;
 
120
 
 
121
    $client = new Client();
 
122
 
 
123
    try {
 
124
        $client->get('http://httpbin.org');
 
125
    } catch (RequestException $e) {
 
126
        echo $e->getRequest() . "\n";
 
127
        if ($e->hasResponse()) {
 
128
            echo $e->getResponse() . "\n";
 
129
        }
 
130
    }
 
131
 
 
132
``GuzzleHttp\Exception\RequestException`` always contains a
 
133
``GuzzleHttp\Message\RequestInterface`` object that can be accessed using the
 
134
exception's ``getRequest()`` method.
 
135
 
 
136
A response might be present in the exception. In the event of a networking
 
137
error, no response will be received. You can check if a ``RequestException``
 
138
has a response using the ``hasResponse()`` method. If the exception has a
 
139
response, then you can access the associated
 
140
``GuzzleHttp\Message\ResponseInterface`` using the ``getResponse()`` method of
 
141
the exception.
 
142
 
 
143
HTTP Errors
 
144
~~~~~~~~~~~
 
145
 
 
146
If the ``exceptions`` request option is not set to ``false``, then exceptions
 
147
are thrown for HTTP protocol errors as well:
 
148
``GuzzleHttp\Exception\ClientErrorResponseException`` for 4xx level HTTP
 
149
responses and ``GuzzleHttp\Exception\ServerException`` for 5xx level responses,
 
150
both of which extend from ``GuzzleHttp\Exception\BadResponseException``.
 
151
 
 
152
Creating Requests
 
153
-----------------
 
154
 
 
155
You can create a request without sending it. This is useful for building up
 
156
requests over time or sending requests in parallel.
 
157
 
 
158
.. code-block:: php
 
159
 
 
160
    $request = $client->createRequest('GET', 'http://httpbin.org', [
 
161
        'headers' => ['X-Foo' => 'Bar']
 
162
    ]);
 
163
 
 
164
    // Modify the request as needed
 
165
    $request->setHeader('Baz', 'bar');
 
166
 
 
167
After creating a request, you can send it with the client's ``send()`` method.
 
168
 
 
169
.. code-block:: php
 
170
 
 
171
    $response = $client->send($request);
 
172
 
 
173
Sending Requests in Parallel
 
174
============================
 
175
 
 
176
You can send requests in parallel using a client object's ``sendAll()`` method.
 
177
The ``sendAll()`` method accepts an array or ``\Iterator`` that contains
 
178
``GuzzleHttp\Message\RequestInterface`` objects. In addition to providing the
 
179
requests to send, you can also specify an associative array of options that
 
180
will affect the transfer.
 
181
 
 
182
.. code-block:: php
 
183
 
 
184
    $requests = [
 
185
        $client->createRequest('GET', 'http://httpbin.org'),
 
186
        $client->createRequest('DELETE', 'http://httpbin.org/delete'),
 
187
        $client->createRequest('PUT', 'http://httpbin.org/put', ['body' => 'test'])
 
188
    ];
 
189
 
 
190
    $client->sendAll($requests);
 
191
 
 
192
The ``sendAll()`` method accepts the following associative array of options:
 
193
 
 
194
- **parallel**: Integer representing the maximum number of requests that are
 
195
  allowed to be sent in parallel.
 
196
- **before**: Callable or array representing the event listeners to add to
 
197
  each request's :ref:`before_event` event.
 
198
- **complete**: Callable or array representing the event listeners to add to
 
199
  each request's :ref:`complete_event` event.
 
200
- **error**: Callable or array representing the event listeners to add to
 
201
  each request's :ref:`error_event` event.
 
202
 
 
203
The "before", "complete", and "error" event options accept a callable or an
 
204
array of associative arrays where each associative array contains a "fn" key
 
205
with a callable value, an optional "priority" key representing the event
 
206
priority (with a default value of 0), and an optional "once" key that can be
 
207
set to true so that the event listener will be removed from the request after
 
208
it is first triggered.
 
209
 
 
210
.. code-block:: php
 
211
 
 
212
    use GuzzleHttp\Event\CompleteEvent;
 
213
 
 
214
    // Add a single event listener using a callable.
 
215
    $client->sendAll($requests, [
 
216
        'complete' => function (CompleteEvent $event) {
 
217
            echo 'Completed request to ' . $event->getRequest()->getUrl() . "\n";
 
218
            echo 'Response: ' . $event->getResponse()->getBody() . "\n\n";
 
219
        }
 
220
    ]);
 
221
 
 
222
    // The above is equivalent to the following, but the following structure
 
223
    // allows you to add multiple event listeners to the same event name.
 
224
    $client->sendAll($requests, [
 
225
        'complete' => [
 
226
            [
 
227
                'fn'       => function (CompleteEvent $event) { /* ... */ },
 
228
                'priority' => 0,    // Optional
 
229
                'once'     => false // Optional
 
230
            ]
 
231
        ]
 
232
    ]);
 
233
 
 
234
Asynchronous Response Handling
 
235
------------------------------
 
236
 
 
237
When sending requests in parallel, the request/response/error lifecycle must be
 
238
handled asynchronously. This means that you give the ``sendAll()`` method
 
239
multiple requests and handle the response or errors that is associated with the
 
240
request using event callbacks.
 
241
 
 
242
.. code-block:: php
 
243
 
 
244
    use GuzzleHttp\Event\ErrorEvent;
 
245
 
 
246
    $client->sendAll($requests, [
 
247
        'complete' => function (CompleteEvent $event) {
 
248
            echo 'Completed request to ' . $event->getRequest()->getUrl() . "\n";
 
249
            echo 'Response: ' . $event->getResponse()->getBody() . "\n\n";
 
250
            // Do something with the completion of the request...
 
251
        },
 
252
        'error' => function (ErrorEvent $event) {
 
253
            echo 'Request failed: ' . $event->getRequest()->getUrl() . "\n";
 
254
            echo $event->getException();
 
255
            // Do something to handle the error...
 
256
        }
 
257
    ]);
 
258
 
 
259
The ``GuzzleHttp\Event\ErrorEvent`` event object is emitted when an error
 
260
occurs during a transfer. With this event, you have access to the request that
 
261
was sent, the response that was received (if one was received), access to
 
262
transfer statistics, and the ability to intercept the exception with a
 
263
different ``GuzzleHttp\Message\ResponseInterface`` object. See :doc:`events`
 
264
for more information.
 
265
 
 
266
Handling Errors After Transferring
 
267
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 
268
 
 
269
It sometimes might be easier to handle all of the errors that occurred during a
 
270
transfer after all of the requests have been sent. Here we are adding each
 
271
failed request to an array that we can use to process errors later.
 
272
 
 
273
.. code-block:: php
 
274
 
 
275
    use GuzzleHttp\Event\ErrorEvent;
 
276
 
 
277
    $errors = [];
 
278
    $client->sendAll($requests, [
 
279
        'error' => function (ErrorEvent $event) use (&$errors) {
 
280
            $errors[] = $event;
 
281
        }
 
282
    ]);
 
283
 
 
284
    foreach ($errors as $error) {
 
285
        // Handle the error...
 
286
    }
 
287
 
 
288
Throwing Errors Immediately
 
289
~~~~~~~~~~~~~~~~~~~~~~~~~~~
 
290
 
 
291
It sometimes is useful to throw exceptions immediately when they occur. The
 
292
following example shows how to use an event listener to throw exceptions
 
293
immediately and prevent subsequent requests from being sent.
 
294
 
 
295
.. code-block:: php
 
296
 
 
297
    use GuzzleHttp\Event\ErrorEvent;
 
298
 
 
299
    $client->sendAll($requests, [
 
300
        'error' => function (ErrorEvent $event) {
 
301
            $event->throwImmediately(true);
 
302
        }
 
303
    ]);
 
304
 
 
305
Calling the ``ErrorEvent::throwImmediately()`` instructs the
 
306
``ParallelAdapterInterface`` sending the request to stop sending subsequent
 
307
requests, clean up any opened resources, and throw the exception associated
 
308
with the event as soon as possible. If the error event was not sent by a
 
309
``ParallelAdapterInterface``, then calling  ``throwImmediately()`` has no
 
310
effect.
 
311
 
 
312
.. note::
 
313
 
 
314
    Subsequent listeners of the "error" event can still intercept the error
 
315
    event with a response if needed, which will, as per the standard behavior,
 
316
    prevent the exception from being thrown.
 
317
 
 
318
.. _batch-requests:
 
319
 
 
320
Batching Requests
 
321
-----------------
 
322
 
 
323
Sometimes you just want to send a few requests in parallel and then process
 
324
the results all at once after they've been sent. Guzzle provides a convenience
 
325
function ``GuzzleHttp\batch()`` that makes this very simple:
 
326
 
 
327
.. code-block:: php
 
328
 
 
329
    $client = new GuzzleHttp\Client();
 
330
 
 
331
    $requests = [
 
332
        $client->createRequest('GET', 'http://httpbin.org/get'),
 
333
        $client->createRequest('HEAD', 'http://httpbin.org/get'),
 
334
        $client->createRequest('PUT', 'http://httpbin.org/put'),
 
335
    ];
 
336
 
 
337
    $results = GuzzleHttp\batch($client, $requests);
 
338
 
 
339
    // Results is an SplObjectStorage object where each request is a key
 
340
    foreach ($requests as $request) {
 
341
        echo $request->getUrl() . "\n";
 
342
        // Get the result (either a ResponseInterface or RequestException)
 
343
        $result = $results[$request];
 
344
        if ($result instanceof ResponseInterface) {
 
345
            // Interact with the response directly
 
346
            echo $result->getStatusCode();
 
347
        } else {
 
348
            // Get the exception message
 
349
            echo $result->getMessage();
 
350
        }
 
351
    }
 
352
 
 
353
``GuzzleHttp\batch()`` accepts an optional associative array of options in the
 
354
third argument that allows you to specify the 'before', 'complete' and 'error'
 
355
events as well as specify the maximum number of requests to send in parallel
 
356
using the 'parallel' option key. This options array is the exact same format as
 
357
the options array exposed in ``GuzzleHttp\ClientInterface::sendAll()``.
 
358
 
 
359
.. _request-options:
 
360
 
 
361
Request Options
 
362
===============
 
363
 
 
364
You can customize requests created by a client using **request options**.
 
365
Request options control various aspects of a request including, headers,
 
366
query string parameters, timeout settings, the body of a request, and much
 
367
more.
 
368
 
 
369
All of the following examples use the following client:
 
370
 
 
371
.. code-block:: php
 
372
 
 
373
    $client = new GuzzleHttp\Client(['base_url' => 'http://httpbin.org']);
 
374
 
 
375
headers
 
376
-------
 
377
 
 
378
:Summary: Associative array of headers to add to the request. Each key is the
 
379
    name of a header, and each value is a string or array of strings
 
380
    representing the header field values.
 
381
:Types: array
 
382
:Defaults: None
 
383
 
 
384
.. code-block:: php
 
385
 
 
386
    // Set various headers on a request
 
387
    $client->get('/get', [
 
388
        'headers' => [
 
389
            'User-Agent' => 'testing/1.0',
 
390
            'Accept'     => 'application/json',
 
391
            'X-Foo'      => ['Bar', 'Baz']
 
392
        ]
 
393
    ]);
 
394
 
 
395
body
 
396
----
 
397
 
 
398
:Summary: The ``body`` option is used to control the body of an entity
 
399
    enclosing request (e.g., PUT, POST, PATCH).
 
400
:Types:
 
401
    - string
 
402
    - ``fopen()`` resource
 
403
    - ``GuzzleHttp\Stream\StreamInterface``
 
404
    - ``GuzzleHttp\Post\PostBodyInterface``
 
405
:Default: None
 
406
 
 
407
This setting can be set to any of the following types:
 
408
 
 
409
- string
 
410
 
 
411
  .. code-block:: php
 
412
 
 
413
      // You can send requests that use a string as the message body.
 
414
      $client->put('/put', ['body' => 'foo']);
 
415
 
 
416
- resource returned from ``fopen()``
 
417
 
 
418
  .. code-block:: php
 
419
 
 
420
      // You can send requests that use a stream resource as the body.
 
421
      $resource = fopen('http://httpbin.org', 'r');
 
422
      $client->put('/put', ['body' => $resource]);
 
423
 
 
424
- Array
 
425
 
 
426
  Use an array to send POST style requests that use a
 
427
  ``GuzzleHttp\Post\PostBodyInterface`` object as the body.
 
428
 
 
429
  .. code-block:: php
 
430
 
 
431
      // You can send requests that use a POST body containing fields & files.
 
432
      $client->post('/post', [
 
433
          'body' => [
 
434
              'field' => 'abc',
 
435
              'other_field' => '123',
 
436
              'file_name' => fopen('/path/to/file', 'r')
 
437
          ]
 
438
      ]);
 
439
 
 
440
- ``GuzzleHttp\Stream\StreamInterface``
 
441
 
 
442
  .. code-block:: php
 
443
 
 
444
      // You can send requests that use a Guzzle stream object as the body
 
445
      $stream = GuzzleHttp\Stream\Stream::factory('contents...');
 
446
      $client->post('/post', ['body' => $stream]);
 
447
 
 
448
json
 
449
----
 
450
 
 
451
:Summary: The ``json`` option is used to easily upload JSON encoded data as the
 
452
    body of a request. A Content-Type header of ``application/json`` will be
 
453
    added if no Content-Type header is already present on the message.
 
454
:Types:
 
455
    Any PHP type that can be operated on by PHP's ``json_encode()`` function.
 
456
:Default: None
 
457
 
 
458
.. code-block:: php
 
459
 
 
460
    $request = $client->createRequest('/put', ['json' => ['foo' => 'bar']]);
 
461
    echo $request->getHeader('Content-Type');
 
462
    // application/json
 
463
    echo $request->getBody();
 
464
    // {"foo":"bar"}
 
465
 
 
466
.. note::
 
467
 
 
468
    This request option does not support customizing the Content-Type header
 
469
    or any of the options from PHP's `json_encode() <http://www.php.net/manual/en/function.json-encode.php>`_
 
470
    function. If you need to customize these settings, then you must pass the
 
471
    JSON encoded data into the request yourself using the ``body`` request
 
472
    option and you must specify the correct Content-Type header using the
 
473
    ``headers`` request option.
 
474
 
 
475
query
 
476
-----
 
477
 
 
478
:Summary: Associative array of query string values to add to the request.
 
479
:Types:
 
480
    - array
 
481
    - ``GuzzleHttp\Query``
 
482
:Default: None
 
483
 
 
484
.. code-block:: php
 
485
 
 
486
    // Send a GET request to /get?foo=bar
 
487
    $client->get('/get', ['query' => ['foo' => 'bar']]);
 
488
 
 
489
Query strings specified in the ``query`` option are combined with any query
 
490
string values that are parsed from the URL.
 
491
 
 
492
.. code-block:: php
 
493
 
 
494
    // Send a GET request to /get?abc=123&foo=bar
 
495
    $client->get('/get?abc=123', ['query' => ['foo' => 'bar']]);
 
496
 
 
497
auth
 
498
----
 
499
 
 
500
:Summary: Pass an array of HTTP authentication parameters to use with the
 
501
    request. The array must contain the username in index [0], the password in
 
502
    index [1], and you can optionally provide a built-in authentication type in
 
503
    index [2]. Pass ``null`` to disable authentication for a request.
 
504
:Types:
 
505
    - array
 
506
    - string
 
507
    - null
 
508
:Default: None
 
509
 
 
510
The built-in authentication types are as follows:
 
511
 
 
512
basic
 
513
    Use `basic HTTP authentication <http://www.ietf.org/rfc/rfc2069.txt>`_ in
 
514
    the ``Authorization`` header (the default setting used if none is
 
515
    specified).
 
516
 
 
517
    .. code-block:: php
 
518
 
 
519
        $client->get('/get', ['auth' => ['username', 'password']]);
 
520
 
 
521
digest
 
522
    Use `digest authentication <http://www.ietf.org/rfc/rfc2069.txt>`_ (must be
 
523
    supported by the HTTP adapter).
 
524
 
 
525
    .. code-block:: php
 
526
 
 
527
        $client->get('/get', ['auth' => ['username', 'password', 'digest']]);
 
528
 
 
529
    *This is currently only supported when using the cURL adapter, but creating
 
530
    a replacement that can be used with any HTTP adapter is planned.*
 
531
 
 
532
.. important::
 
533
 
 
534
    The authentication type (whether it's provided as a string or as the third
 
535
    option in an array) is always converted to a lowercase string. Take this
 
536
    into account when implementing custom authentication types and when
 
537
    implementing custom message factories.
 
538
 
 
539
Custom Authentication Schemes
 
540
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 
541
 
 
542
You can also provide a string representing a custom authentication type name.
 
543
When using a custom authentication type string, you will need to implement
 
544
the authentication method in an event listener that checks the ``auth`` request
 
545
option of a request before it is sent. Authentication listeners that require
 
546
a request is not modified after they are signed should have a very low priority
 
547
to ensure that they are fired last or near last in the event chain.
 
548
 
 
549
.. code-block:: php
 
550
 
 
551
    use GuzzleHttp\Event\BeforeEvent;
 
552
    use GuzzleHttp\Event\RequestEvents;
 
553
 
 
554
    /**
 
555
     * Custom authentication listener that handles the "foo" auth type.
 
556
     *
 
557
     * Listens to the "before" event of a request and only modifies the request
 
558
     * when the "auth" config setting of the request is "foo".
 
559
     */
 
560
    class FooAuth implements GuzzleHttp\Event\SubscriberInterface
 
561
    {
 
562
        private $password;
 
563
 
 
564
        public function __construct($password)
 
565
        {
 
566
            $this->password = $password;
 
567
        }
 
568
 
 
569
        public function getEvents()
 
570
        {
 
571
            return ['before' => ['sign', RequestEvents::SIGN_REQUEST]];
 
572
        }
 
573
 
 
574
        public function sign(BeforeEvent $e)
 
575
        {
 
576
            if ($e->getRequest()->getConfig()['auth'] == 'foo') {
 
577
                $e->getRequest()->setHeader('X-Foo', 'Foo ' . $this->password);
 
578
            }
 
579
        }
 
580
    }
 
581
 
 
582
    $client->getEmitter()->attach(new FooAuth('password'));
 
583
    $client->get('/', ['auth' => 'foo']);
 
584
 
 
585
Adapter Specific Authentication Schemes
 
586
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 
587
 
 
588
If you need to use authentication methods provided by cURL (e.g., NTLM, GSS,
 
589
etc.), then you need to specify a curl adapter option in the ``options``
 
590
request option array. See :ref:`config-option` for more information.
 
591
 
 
592
.. _cookies-option:
 
593
 
 
594
cookies
 
595
-------
 
596
 
 
597
:Summary: Specifies whether or not cookies are used in a request or what cookie
 
598
    jar to use or what cookies to send.
 
599
:Types:
 
600
    - bool
 
601
    - array
 
602
    - ``GuzzleHttp\Cookie\CookieJarInterface``
 
603
:Default: None
 
604
 
 
605
Set to ``true`` to use a shared cookie session associated with the client.
 
606
 
 
607
.. code-block:: php
 
608
 
 
609
    // Enable cookies using the shared cookie jar of the client.
 
610
    $client->get('/get', ['cookies' => true]);
 
611
 
 
612
Pass an associative array containing cookies to send in the request and start a
 
613
new cookie session.
 
614
 
 
615
.. code-block:: php
 
616
 
 
617
    // Enable cookies and send specific cookies
 
618
    $client->get('/get', ['cookies' => ['foo' => 'bar']]);
 
619
 
 
620
Set to a ``GuzzleHttp\Cookie\CookieJarInterface`` object to use an existing
 
621
cookie jar.
 
622
 
 
623
.. code-block:: php
 
624
 
 
625
    $jar = new GuzzleHttp\Cookie\CookieJar();
 
626
    $client->get('/get', ['cookies' => $jar]);
 
627
 
 
628
.. _allow_redirects-option:
 
629
 
 
630
allow_redirects
 
631
---------------
 
632
 
 
633
:Summary: Describes the redirect behavior of a request
 
634
:Types:
 
635
    - bool
 
636
    - array
 
637
:Default: ``['max' => 5, 'strict' => false, 'referer' => true]``
 
638
 
 
639
Set to ``false`` to disable redirects.
 
640
 
 
641
.. code-block:: php
 
642
 
 
643
    $res = $client->get('/redirect/3', ['allow_redirects' => false]);
 
644
    echo $res->getStatusCode();
 
645
    // 302
 
646
 
 
647
Set to ``true`` (the default setting) to enable normal redirects with a maximum
 
648
number of 5 redirects.
 
649
 
 
650
.. code-block:: php
 
651
 
 
652
    $res = $client->get('/redirect/3');
 
653
    echo $res->getStatusCode();
 
654
    // 200
 
655
 
 
656
Pass an associative array containing the 'max' key to specify the maximum
 
657
number of redirects, optionally provide a 'strict' key value to specify
 
658
whether or not to use strict RFC compliant redirects (meaning redirect POST
 
659
requests with POST requests vs. doing what most browsers do which is redirect
 
660
POST requests with GET requests), and optionally provide a 'referer' key to
 
661
specify whether or not the "Referer" header should be added when redirecting.
 
662
 
 
663
.. code-block:: php
 
664
 
 
665
    $res = $client->get('/redirect/3', [
 
666
        'allow_redirects' => [
 
667
            'max'     => 10,
 
668
            'strict'  => true,
 
669
            'referer' => true
 
670
        ]
 
671
    ]);
 
672
    echo $res->getStatusCode();
 
673
    // 200
 
674
 
 
675
decode_content
 
676
--------------
 
677
 
 
678
:Summary: Specify whether or not ``Content-Encoding`` responses (gzip,
 
679
    deflate, etc.) are automatically decoded.
 
680
:Types:
 
681
    - string
 
682
    - bool
 
683
:Default: ``true``
 
684
 
 
685
This option can be used to control how content-encoded response bodies are
 
686
handled. By default, ``decode_content`` is set to true, meaning any gzipped
 
687
or deflated response will be decoded by Guzzle.
 
688
 
 
689
When set to ``false``, the body of a response is never decoded, meaning the
 
690
bytes pass through the adapter unchanged.
 
691
 
 
692
.. code-block:: php
 
693
 
 
694
    // Request gzipped data, but do not decode it while downloading
 
695
    $client->get('/foo.js', [
 
696
        'headers'        => ['Accept-Encoding' => 'gzip'],
 
697
        'decode_content' => false
 
698
    ]);
 
699
 
 
700
When set to a string, the bytes of a response are decoded and the string value
 
701
provided to the ``decode_content`` option is passed as the ``Accept-Encoding``
 
702
header of the request.
 
703
 
 
704
.. code-block:: php
 
705
 
 
706
    // Pass "gzip" as the Accept-Encoding header.
 
707
    $client->get('/foo.js', ['decode_content' => 'gzip']);
 
708
 
 
709
.. _save_to-option:
 
710
 
 
711
save_to
 
712
-------
 
713
 
 
714
:Summary: Specify where the body of a response will be saved.
 
715
:Types:
 
716
    - string
 
717
    - ``fopen()`` resource
 
718
    - ``GuzzleHttp\Stream\StreamInterface``
 
719
:Default: PHP temp stream
 
720
 
 
721
Pass a string to specify the path to a file that will store the contents of the
 
722
response body:
 
723
 
 
724
.. code-block:: php
 
725
 
 
726
    $client->get('/stream/20', ['save_to' => '/path/to/file']);
 
727
 
 
728
Pass a resource returned from ``fopen()`` to write the response to a PHP stream:
 
729
 
 
730
.. code-block:: php
 
731
 
 
732
    $resource = fopen('/path/to/file', 'w');
 
733
    $client->get('/stream/20', ['save_to' => $resource]);
 
734
 
 
735
Pass a ``GuzzleHttp\Stream\StreamInterface`` object to stream the response body
 
736
to an open Guzzle stream:
 
737
 
 
738
.. code-block:: php
 
739
 
 
740
    $resource = fopen('/path/to/file', 'w');
 
741
    $stream = GuzzleHttp\Stream\Stream::factory($resource);
 
742
    $client->get('/stream/20', ['save_to' => $stream]);
 
743
 
 
744
.. _events-option:
 
745
 
 
746
events
 
747
------
 
748
 
 
749
:Summary: An associative array mapping event names to a callable. Or an
 
750
    associative array containing the 'fn' key that maps to a callable, an
 
751
    optional 'priority' key used to specify the event priority, and an optional
 
752
    'once' key used to specify if the event should remove itself the first time
 
753
    it is triggered.
 
754
:Types: array
 
755
:Default: None
 
756
 
 
757
.. code-block:: php
 
758
 
 
759
    use GuzzleHttp\Event\BeforeEvent;
 
760
    use GuzzleHttp\Event\HeadersEvent;
 
761
    use GuzzleHttp\Event\CompleteEvent;
 
762
    use GuzzleHttp\Event\ErrorEvent;
 
763
 
 
764
    $client->get('/', [
 
765
        'events' => [
 
766
            'before' => function (BeforeEvent $e) { echo 'Before'; },
 
767
            'headers' => function (HeadersEvent $e) { echo 'Headers'; },
 
768
            'complete' => function (CompleteEvent $e) { echo 'Complete'; },
 
769
            'error' => function (ErrorEvent $e) { echo 'Error'; },
 
770
        ]
 
771
    ]);
 
772
 
 
773
Here's an example of using the associative array format for control over the
 
774
priority and whether or not an event should be triggered more than once.
 
775
 
 
776
.. code-block:: php
 
777
 
 
778
    $client->get('/', [
 
779
        'events' => [
 
780
            'before' => [
 
781
                'fn'       => function (BeforeEvent $e) { echo 'Before'; },
 
782
                'priority' => 100,
 
783
                'once'     => true
 
784
            ]
 
785
        ]
 
786
    ]);
 
787
 
 
788
.. _subscribers-option:
 
789
 
 
790
subscribers
 
791
-----------
 
792
 
 
793
:Summary: Array of event subscribers to add to the request. Each value in the
 
794
    array must be an instance of ``GuzzleHttp\Event\SubscriberInterface``.
 
795
:Types: array
 
796
:Default: None
 
797
 
 
798
.. code-block:: php
 
799
 
 
800
    use GuzzleHttp\Subscriber\History;
 
801
    use GuzzleHttp\Subscriber\Mock;
 
802
    use GuzzleHttp\Message\Response;
 
803
 
 
804
    $history = new History();
 
805
    $mock = new Mock([new Response(200)]);
 
806
    $client->get('/', ['subscribers' => [$history, $mock]]);
 
807
 
 
808
    echo $history;
 
809
    // Outputs the request and response history
 
810
 
 
811
.. _exceptions-option:
 
812
 
 
813
exceptions
 
814
----------
 
815
 
 
816
:Summary: Set to ``false`` to disable throwing exceptions on an HTTP protocol
 
817
    errors (i.e., 4xx and 5xx responses). Exceptions are thrown by default when
 
818
    HTTP protocol errors are encountered.
 
819
:Types: bool
 
820
:Default: ``true``
 
821
 
 
822
.. code-block:: php
 
823
 
 
824
    $client->get('/status/500');
 
825
    // Throws a GuzzleHttp\Exception\ServerException
 
826
 
 
827
    $res = $client->get('/status/500', ['exceptions' => false]);
 
828
    echo $res->getStatusCode();
 
829
    // 500
 
830
 
 
831
.. _timeout-option:
 
832
 
 
833
timeout
 
834
-------
 
835
 
 
836
:Summary: Float describing the timeout of the request in seconds. Use ``0``
 
837
    to wait indefinitely (the default behavior).
 
838
:Types: float
 
839
:Default: ``0``
 
840
 
 
841
.. code-block:: php
 
842
 
 
843
    // Timeout if a server does not return a response in 3.14 seconds.
 
844
    $client->get('/delay/5', ['timeout' => 3.14]);
 
845
    // PHP Fatal error:  Uncaught exception 'GuzzleHttp\Exception\RequestException'
 
846
 
 
847
.. _connect_timeout-option:
 
848
 
 
849
connect_timeout
 
850
---------------
 
851
 
 
852
:Summary: Float describing the number of seconds to wait while trying to connect
 
853
    to a server. Use ``0`` to wait indefinitely (the default behavior).
 
854
:Types: float
 
855
:Default: ``0``
 
856
 
 
857
.. code-block:: php
 
858
 
 
859
    // Timeout if the client fails to connect to the server in 3.14 seconds.
 
860
    $client->get('/delay/5', ['connect_timeout' => 3.14]);
 
861
 
 
862
.. note::
 
863
 
 
864
    This setting must be supported by the HTTP adapter used to send a request.
 
865
    ``connect_timeout`` is currently only supported by the built-in cURL
 
866
    adapter.
 
867
 
 
868
.. _verify-option:
 
869
 
 
870
verify
 
871
------
 
872
 
 
873
:Summary: Describes the SSL certificate verification behavior of a request.
 
874
    Set to ``true`` to enable SSL certificate verification (the default). Set
 
875
    to ``false`` to disable certificate verification (this is insecure!). Set
 
876
    to a string to provide the path to a CA bundle to enable verification using
 
877
    a custom certificate.
 
878
:Types:
 
879
    - bool
 
880
    - string
 
881
:Default: ``true``
 
882
 
 
883
.. code-block:: php
 
884
 
 
885
    // Use a custom SSL certificate
 
886
    $client->get('/', ['verify' => '/path/to/cert.pem']);
 
887
 
 
888
    // Disable validation
 
889
    $client->get('/', ['verify' => false]);
 
890
 
 
891
.. _cert-option:
 
892
 
 
893
cert
 
894
----
 
895
 
 
896
:Summary: Set to a string to specify the path to a file containing a PEM
 
897
    formatted client side certificate. If a password is required, then set to
 
898
    an array containing the path to the PEM file in the first array element
 
899
    followed by the password required for the certificate in the second array
 
900
    element.
 
901
:Types:
 
902
    - string
 
903
    - array
 
904
:Default: None
 
905
 
 
906
.. code-block:: php
 
907
 
 
908
    $client->get('/', ['cert' => ['/path/server.pem', 'password']]);
 
909
 
 
910
.. _ssl_key-option:
 
911
 
 
912
ssl_key
 
913
-------
 
914
 
 
915
:Summary: Specify the path to a file containing a private SSL key in PEM
 
916
    format. If a password is required, then set to an array containing the path
 
917
    to the SSL key in the first array element followed by the password required
 
918
    for the certificate in the second element.
 
919
:Types:
 
920
    - string
 
921
    - array
 
922
:Default: None
 
923
 
 
924
.. note::
 
925
 
 
926
    ``ssl_key`` is implemented by HTTP adapters. This is currently only
 
927
    supported by the cURL adapter, but might be supported by other third-part
 
928
    adapters.
 
929
 
 
930
.. _proxy-option:
 
931
 
 
932
proxy
 
933
-----
 
934
 
 
935
:Summary: Pass a string to specify an HTTP proxy, or an array to specify
 
936
    different proxies for different protocols.
 
937
:Types:
 
938
    - string
 
939
    - array
 
940
:Default: None
 
941
 
 
942
Pass a string to specify a proxy for all protocols.
 
943
 
 
944
.. code-block:: php
 
945
 
 
946
    $client->get('/', ['proxy' => 'tcp://localhost:8125']);
 
947
 
 
948
Pass an associative array to specify HTTP proxies for specific URI schemes
 
949
(i.e., "http", "https").
 
950
 
 
951
.. code-block:: php
 
952
 
 
953
    $client->get('/', [
 
954
        'proxy' => [
 
955
            'http'  => 'tcp://localhost:8125', // Use this proxy with "http"
 
956
            'https' => 'tcp://localhost:9124'  // Use this proxy with "https"
 
957
        ]
 
958
    ]);
 
959
 
 
960
.. note::
 
961
 
 
962
    You can provide proxy URLs that contain a scheme, username, and password.
 
963
    For example, ``"http://username:password@192.168.16.1:10"``.
 
964
 
 
965
.. _debug-option:
 
966
 
 
967
debug
 
968
-----
 
969
 
 
970
:Summary: Set to ``true`` or set to a PHP stream returned by ``fopen()`` to
 
971
    enable debug output with the adapter used to send a request. For example,
 
972
    when using cURL to transfer requests, cURL's verbose of ``CURLOPT_VERBOSE``
 
973
    will be emitted. When using the PHP stream wrapper, stream wrapper
 
974
    notifications will be emitted. If set to true, the output is written to
 
975
    PHP's STDOUT. If a PHP stream is provided, output is written to the stream.
 
976
:Types:
 
977
    - bool
 
978
    - ``fopen()`` resource
 
979
:Default: None
 
980
 
 
981
.. code-block:: php
 
982
 
 
983
    $client->get('/get', ['debug' => true]);
 
984
 
 
985
Running the above example would output something like the following:
 
986
 
 
987
::
 
988
 
 
989
    * About to connect() to httpbin.org port 80 (#0)
 
990
    *   Trying 107.21.213.98... * Connected to httpbin.org (107.21.213.98) port 80 (#0)
 
991
    > GET /get HTTP/1.1
 
992
    Host: httpbin.org
 
993
    User-Agent: Guzzle/4.0 curl/7.21.4 PHP/5.5.7
 
994
 
 
995
    < HTTP/1.1 200 OK
 
996
    < Access-Control-Allow-Origin: *
 
997
    < Content-Type: application/json
 
998
    < Date: Sun, 16 Feb 2014 06:50:09 GMT
 
999
    < Server: gunicorn/0.17.4
 
1000
    < Content-Length: 335
 
1001
    < Connection: keep-alive
 
1002
    <
 
1003
    * Connection #0 to host httpbin.org left intact
 
1004
 
 
1005
.. _stream-option:
 
1006
 
 
1007
stream
 
1008
------
 
1009
 
 
1010
:Summary: Set to ``true`` to stream a response rather than download it all
 
1011
    up-front.
 
1012
:Types: bool
 
1013
:Default: ``false``
 
1014
 
 
1015
.. code-block:: php
 
1016
 
 
1017
    $response = $client->get('/stream/20', ['stream' => true]);
 
1018
    // Read bytes off of the stream until the end of the stream is reached
 
1019
    $body = $response->getBody();
 
1020
    while (!$body->eof()) {
 
1021
        echo $body->read(1024);
 
1022
    }
 
1023
 
 
1024
.. note::
 
1025
 
 
1026
    Streaming response support must be implemented by the HTTP adapter used by
 
1027
    a client. This option might not be supported by every HTTP adapter, but the
 
1028
    interface of the response object remains the same regardless of whether or
 
1029
    not it is supported by the adapter.
 
1030
 
 
1031
.. _expect-option:
 
1032
 
 
1033
expect
 
1034
------
 
1035
 
 
1036
:Summary: Controls the behavior of the "Expect: 100-Continue" header.
 
1037
:Types:
 
1038
    - bool
 
1039
    - integer
 
1040
:Default: ``1048576``
 
1041
 
 
1042
Set to ``true`` to enable the "Expect: 100-Continue" header for all requests
 
1043
that sends a body. Set to ``false`` to disable the "Expect: 100-Continue"
 
1044
header for all requests. Set to a number so that the size of the payload must
 
1045
be greater than the number in order to send the Expect header. Setting to a
 
1046
number will send the Expect header for all requests in which the size of the
 
1047
payload cannot be determined or where the body is not rewindable.
 
1048
 
 
1049
By default, Guzzle will add the "Expect: 100-Continue" header when the size of
 
1050
the body of a request is greater than 1 MB and a request is using HTTP/1.1.
 
1051
 
 
1052
.. note::
 
1053
 
 
1054
    This option only takes effect when using HTTP/1.1. The HTTP/1.0 and
 
1055
    HTTP/2.0 protocols do not support the "Expect: 100-Continue" header.
 
1056
    Support for handling the "Expect: 100-Continue" workflow must be
 
1057
    implemented by Guzzle HTTP adapters used by a client.
 
1058
 
 
1059
.. _version-option:
 
1060
 
 
1061
version
 
1062
-------
 
1063
 
 
1064
:Summary: Protocol version to use with the request.
 
1065
:Types: string, float
 
1066
:Default: ``1.1``
 
1067
 
 
1068
.. code-block:: php
 
1069
 
 
1070
    // Force HTTP/1.0
 
1071
    $request = $client->createRequest('GET', '/get', ['version' => 1.0]);
 
1072
    echo $request->getProtocolVersion();
 
1073
    // 1.0
 
1074
 
 
1075
.. _config-option:
 
1076
 
 
1077
config
 
1078
------
 
1079
 
 
1080
:Summary: Associative array of config options that are forwarded to a request's
 
1081
    configuration collection. These values are used as configuration options
 
1082
    that can be consumed by plugins and adapters.
 
1083
:Types: array
 
1084
:Default: None
 
1085
 
 
1086
.. code-block:: php
 
1087
 
 
1088
    $request = $client->createRequest('GET', '/get', ['config' => ['foo' => 'bar']]);
 
1089
    echo $request->getConfig('foo');
 
1090
    // 'bar'
 
1091
 
 
1092
Some HTTP adapters allow you to specify custom adapter-specific settings. For
 
1093
example, you can pass custom cURL options to requests by passing an associative
 
1094
array in the ``config`` request option under the ``curl`` key.
 
1095
 
 
1096
.. code-block:: php
 
1097
 
 
1098
    // Use custom cURL options with the request. This example uses NTLM auth
 
1099
    // to authenticate with a server.
 
1100
    $client->get('/', [
 
1101
        'config' => [
 
1102
            'curl' => [
 
1103
                CURLOPT_HTTPAUTH => CURLAUTH_NTLM,
 
1104
                CURLOPT_USERPWD  => 'username:password'
 
1105
            ]
 
1106
        ]
 
1107
    ]);
 
1108
 
 
1109
Event Subscribers
 
1110
=================
 
1111
 
 
1112
Requests emit lifecycle events when they are transferred. A client object has a
 
1113
``GuzzleHttp\Common\EventEmitter`` object that can be used to add event
 
1114
*listeners* and event *subscribers* to all requests created by the client.
 
1115
 
 
1116
.. important::
 
1117
 
 
1118
    **Every** event listener or subscriber added to a client will be added to
 
1119
    every request created by the client.
 
1120
 
 
1121
.. code-block:: php
 
1122
 
 
1123
    use GuzzleHttp\Client;
 
1124
    use GuzzleHttp\Event\BeforeEvent;
 
1125
 
 
1126
    $client = new Client();
 
1127
 
 
1128
    // Add a listener that will echo out requests before they are sent
 
1129
    $client->getEmitter()->on('before', function (BeforeEvent $e) {
 
1130
        echo 'About to send request: ' . $e->getRequest();
 
1131
    });
 
1132
 
 
1133
    $client->get('http://httpbin.org/get');
 
1134
    // Outputs the request as a string because of the event
 
1135
 
 
1136
See :doc:`events` for more information on the event system used in Guzzle.
 
1137
 
 
1138
Environment Variables
 
1139
=====================
 
1140
 
 
1141
Guzzle exposes a few environment variables that can be used to customize the
 
1142
behavior of the library.
 
1143
 
 
1144
``GUZZLE_CURL_SELECT_TIMEOUT``
 
1145
    Controls the duration in seconds that ``GuzzleHttp\Adapter\Curl\MultiAdapter``
 
1146
    will use when selecting handles using ``curl_multi_select()``. Some systems
 
1147
    have issues with PHP's implementation of ``curl_multi_select()`` where
 
1148
    calling this function always results in waiting for the maximum duration of
 
1149
    the timeout.
 
1150
``HTTP_PROXY``
 
1151
    Defines the proxy to use when sending requests using the "http" protocol.
 
1152
``HTTPS_PROXY``
 
1153
    Defines the proxy to use when sending requests using the "https" protocol.
 
1154
 
 
1155
Relevant ini Settings
 
1156
---------------------
 
1157
 
 
1158
Guzzle can utilize PHP ini settings when configuring clients.
 
1159
 
 
1160
``openssl.cafile``
 
1161
    Specifies the path on disk to a CA file in PEM format to use when sending
 
1162
    requests over "https". See: https://wiki.php.net/rfc/tls-peer-verification#phpini_defaults