~tcuthbert/wordpress/openstack-objectstorage

« back to all changes in this revision

Viewing changes to vendor/guzzlehttp/guzzle/docs/http-messages.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
Request and Response Messages
 
3
=============================
 
4
 
 
5
Guzzle is an HTTP client that sends HTTP requests to a server and receives HTTP
 
6
responses. Both requests and responses are referred to as messages.
 
7
 
 
8
Headers
 
9
=======
 
10
 
 
11
Both request and response messages contain HTTP headers.
 
12
 
 
13
Complex Headers
 
14
---------------
 
15
 
 
16
Some headers contain additional key value pair information. For example, Link
 
17
headers contain a link and several key value pairs:
 
18
 
 
19
::
 
20
 
 
21
    <http://foo.com>; rel="thing"; type="image/jpeg"
 
22
 
 
23
Guzzle provides a convenience feature that can be used to parse these types of
 
24
headers:
 
25
 
 
26
.. code-block:: php
 
27
 
 
28
    use GuzzleHttp\Message\Request;
 
29
 
 
30
    $request = new Request('GET', '/', [
 
31
        'Link' => '<http:/.../front.jpeg>; rel="front"; type="image/jpeg"'
 
32
    ]);
 
33
 
 
34
    $parsed = Request::parseHeader($request, 'Link');
 
35
    echo json_encode($parsed, JSON_PRETTY_PRINT);
 
36
 
 
37
::
 
38
 
 
39
    [
 
40
        {
 
41
            "0": "<http:\/...\/front.jpeg>",
 
42
            "rel": "front",
 
43
            "type": "image\/jpeg"
 
44
        }
 
45
    ]
 
46
 
 
47
The result contains a hash of key value pairs. Header values that have no key
 
48
(i.e., the link) are indexed numerically while headers parts that form a key
 
49
value pair are added as a key value pair.
 
50
 
 
51
See :ref:`headers` for information on how the headers of a request and response
 
52
can be accessed and modified.
 
53
 
 
54
Body
 
55
====
 
56
 
 
57
Both request and response messages can contain a body.
 
58
 
 
59
You can check to see if a request or response has a body using the
 
60
``getBody()`` method:
 
61
 
 
62
.. code-block:: php
 
63
 
 
64
    $response = GuzzleHttp\get('http://httpbin.org/get');
 
65
    if ($response->getBody()) {
 
66
        echo $response->getBody();
 
67
        // JSON string: { ... }
 
68
    }
 
69
 
 
70
The body used in request and response objects is a
 
71
``GuzzleHttp\Stream\StreamInterface``. This stream is used for both uploading
 
72
data and downloading data. Guzzle will, by default, store the body of a message
 
73
in a stream that uses PHP temp streams. When the size of the body exceeds
 
74
2 MB, the stream will automatically switch to storing data on disk rather than
 
75
in memory (protecting your application from memory exhaustion).
 
76
 
 
77
You can change the body used in a request or response using the ``setBody()``
 
78
method:
 
79
 
 
80
.. code-block:: php
 
81
 
 
82
    use GuzzleHttp\Stream\Stream;
 
83
    $request = $client->createRequest('PUT', 'http://httpbin.org/put');
 
84
    $request->setBody(Stream::factory('foo'));
 
85
 
 
86
The easiest way to create a body for a request is using the static
 
87
``GuzzleHttp\Stream\Stream::factory()`` method. This method accepts various
 
88
inputs like strings, resources returned from ``fopen()``, and other
 
89
``GuzzleHttp\Stream\StreamInterface`` objects.
 
90
 
 
91
The body of a request or response can be cast to a string or you can read and
 
92
write bytes off of the stream as needed.
 
93
 
 
94
.. code-block:: php
 
95
 
 
96
    use GuzzleHttp\Stream\Stream;
 
97
    $request = $client->createRequest('PUT', 'http://httpbin.org/put', ['body' => 'testing...']);
 
98
 
 
99
    echo $request->getBody()->read(4);
 
100
    // test
 
101
    echo $request->getBody()->read(4);
 
102
    // ing.
 
103
    echo $request->getBody()->read(1024);
 
104
    // ..
 
105
    var_export($request->eof());
 
106
    // true
 
107
 
 
108
You can find out more about Guzzle stream objects in :doc:`streams`.
 
109
 
 
110
Requests
 
111
========
 
112
 
 
113
Requests are sent from a client to a server. Requests include the method to
 
114
be applied to a resource, the identifier of the resource, and the protocol
 
115
version to use.
 
116
 
 
117
Clients are used to create request messages. More precisely, clients use
 
118
a ``GuzzleHttp\Message\MessageFactoryInterface`` to create request messages.
 
119
You create requests with a client using the ``createRequest()`` method.
 
120
 
 
121
.. code-block:: php
 
122
 
 
123
    // Create a request but don't send it immediately
 
124
    $request = $client->createRequest('GET', 'http://httpbin.org/get');
 
125
 
 
126
Request Methods
 
127
---------------
 
128
 
 
129
When creating a request, you are expected to provide the HTTP method you wish
 
130
to perform. You can specify any method you'd like, including a custom method
 
131
that might not be part of RFC 2616 (like "MOVE").
 
132
 
 
133
.. code-block:: php
 
134
 
 
135
    // Create a request using a completely custom HTTP method
 
136
    $request = $client->createRequest('MOVE', 'http://httpbin.org/move', ['exceptions' => false]);
 
137
 
 
138
    echo $request->getMethod();
 
139
    // MOVE
 
140
 
 
141
    $response = $client->send($request);
 
142
    echo $response->getStatusCode();
 
143
    // 405
 
144
 
 
145
You can create and send a request using methods on a client that map to the
 
146
HTTP method you wish to use.
 
147
 
 
148
:GET: ``$client->get('http://httpbin.org/get', [/** options **/])``
 
149
:POST: ``$client->post('http://httpbin.org/post', [/** options **/])``
 
150
:HEAD: ``$client->head('http://httpbin.org/get', [/** options **/])``
 
151
:PUT: ``$client->put('http://httpbin.org/put', [/** options **/])``
 
152
:DELETE: ``$client->delete('http://httpbin.org/delete', [/** options **/])``
 
153
:OPTIONS: ``$client->options('http://httpbin.org/get', [/** options **/])``
 
154
:PATCH: ``$client->patch('http://httpbin.org/put', [/** options **/])``
 
155
 
 
156
.. code-block:: php
 
157
 
 
158
    $response = $client->patch('http://httpbin.org/patch', ['body' => 'content']);
 
159
 
 
160
Request URI
 
161
-----------
 
162
 
 
163
The resource you are requesting with an HTTP request is identified by the
 
164
path of the request, the query string, and the "Host" header of the request.
 
165
 
 
166
When creating a request, you can provide the entire resource URI as a URL.
 
167
 
 
168
.. code-block:: php
 
169
 
 
170
    $response = $client->get('http://httbin.org/get?q=foo');
 
171
 
 
172
Using the above code, you will send a request that uses ``httpbin.org`` as
 
173
the Host header, sends the request over port 80, uses ``/get`` as the path,
 
174
and sends ``?q=foo`` as the query string. All of this is parsed automatically
 
175
from the provided URI.
 
176
 
 
177
Sometimes you don't know what the entire request will be when it is created.
 
178
In these cases, you can modify the request as needed before sending it using
 
179
the ``createRequest()`` method of the client and methods on the request that
 
180
allow you to change it.
 
181
 
 
182
.. code-block:: php
 
183
 
 
184
    $request = $client->createRequest('GET', 'http://httbin.org');
 
185
 
 
186
You can change the path of the request using ``setPath()``:
 
187
 
 
188
.. code-block:: php
 
189
 
 
190
    $request->setPath('/get');
 
191
    echo $request->getPath();
 
192
    // /get
 
193
    echo $request->getUrl();
 
194
    // http://httpbin.com/get
 
195
 
 
196
Scheme
 
197
~~~~~~
 
198
 
 
199
The `scheme <http://tools.ietf.org/html/rfc3986#section-3.1>`_ of a request
 
200
specifies the protocol to use when sending the request. When using Guzzle, the
 
201
scheme can be set to "http" or "https".
 
202
 
 
203
You can change the scheme of the request using the ``setScheme()`` method:
 
204
 
 
205
.. code-block:: php
 
206
 
 
207
    $request = $client->createRequest('GET', 'http://httbin.org');
 
208
    $request->setScheme('https');
 
209
    echo $request->getScheme();
 
210
    // https
 
211
    echo $request->getUrl();
 
212
    // https://httpbin.com/get
 
213
 
 
214
Port
 
215
~~~~
 
216
 
 
217
No port is necessary when using the "http" or "https" schemes, but you can
 
218
override the port using ``setPort()``. If you need to modify the port used with
 
219
the specified scheme from the default setting, then you must use the
 
220
``setPort()`` method.
 
221
 
 
222
.. code-block:: php
 
223
 
 
224
    $request = $client->createRequest('GET', 'http://httbin.org');
 
225
    $request->setPort(8080);
 
226
    echo $request->getPort();
 
227
    // 8080
 
228
    echo $request->getUrl();
 
229
    // https://httpbin.com:8080/get
 
230
 
 
231
    // Set the port back to the default value for the scheme
 
232
    $request->setPort(443);
 
233
    echo $request->getUrl();
 
234
    // https://httpbin.com/get
 
235
 
 
236
Query string
 
237
~~~~~~~~~~~~
 
238
 
 
239
You can get the query string of the request using the ``getQuery()`` method.
 
240
This method returns a ``GuzzleHttp\Query`` object. A Query object can be
 
241
accessed like a PHP array, iterated in a foreach statement like a PHP array,
 
242
and cast to a string.
 
243
 
 
244
.. code-block:: php
 
245
 
 
246
    $request = $client->createRequest('GET', 'http://httbin.org');
 
247
    $query = $request->getQuery();
 
248
    $query['foo'] = 'bar';
 
249
    $query['baz'] = 'bam';
 
250
    $query['bam'] = ['test' => 'abc'];
 
251
 
 
252
    echo $request->getQuery();
 
253
    // foo=bar&baz=bam&bam%5Btest%5D=abc
 
254
 
 
255
    echo $request->getQuery()['foo'];
 
256
    // bar
 
257
    echo $request->getQuery()->get('foo');
 
258
    // bar
 
259
    echo $request->getQuery()->get('foo');
 
260
    // bar
 
261
 
 
262
    var_export($request->getQuery()['bam']);
 
263
    // array('test' => 'abc')
 
264
 
 
265
    foreach ($query as $key => $value) {
 
266
        var_export($value);
 
267
    }
 
268
 
 
269
    echo $request->getUrl();
 
270
    // https://httpbin.com/get?foo=bar&baz=bam&bam%5Btest%5D=abc
 
271
 
 
272
Query Aggregators
 
273
^^^^^^^^^^^^^^^^^
 
274
 
 
275
Query objects can store scalar values or arrays of values. When an array of
 
276
values is added to a query object, the query object uses a query aggregator to
 
277
convert the complex structure into a string. Query objects will use
 
278
`PHP style query strings <http://www.php.net/http_build_query>`_ when complex
 
279
query string parameters are converted to a string. You can customize how
 
280
complex query string parameters are aggregated using the ``setAggregator()``
 
281
method of a query string object.
 
282
 
 
283
.. code-block:: php
 
284
 
 
285
    $query->setAggregator($query::duplicateAggregator());
 
286
 
 
287
In the above example, we've changed the query object to use the
 
288
"duplicateAggregator". This aggregator will allow duplicate entries to appear
 
289
in a query string rather than appending "[n]" to each value. So if you had a
 
290
query string with ``['a' => ['b', 'c']]``, the duplicate aggregator would
 
291
convert this to "a=b&a=c" while the default aggregator would convert this to
 
292
"a[0]=b&a[1]=c" (with urlencoded brackets).
 
293
 
 
294
The ``setAggregator()`` method accepts a ``callable`` which is used to convert
 
295
a deeply nested array of query string variables into a flattened array of key
 
296
value pairs. The callable accepts an array of query data and returns a
 
297
flattened array of key value pairs where each value is an array of strings.
 
298
You can use the ``GuzzleHttp\Query::walkQuery()`` static function to easily
 
299
create custom query aggregators.
 
300
 
 
301
Host
 
302
~~~~
 
303
 
 
304
You can change the host header of the request in a predictable way using the
 
305
``setHost()`` method of a request:
 
306
 
 
307
.. code-block:: php
 
308
 
 
309
    $request->setHost('www.google.com');
 
310
    echo $request->getHost();
 
311
    // www.google.com
 
312
    echo $request->getUrl();
 
313
    // https://www.google.com/get?foo=bar&baz=bam
 
314
 
 
315
.. note::
 
316
 
 
317
    The Host header can also be changed by modifying the Host header of a
 
318
    request directly, but modifying the Host header directly could result in
 
319
    sending a request to a different Host than what is specified in the Host
 
320
    header (sometimes this is actually the desired behavior).
 
321
 
 
322
Resource
 
323
~~~~~~~~
 
324
 
 
325
You can use the ``getResource()`` method of a request to return the path and
 
326
query string of a request in a single string.
 
327
 
 
328
.. code-block:: php
 
329
 
 
330
    $request = $client->createRequest('GET', 'http://httpbin.org/get?baz=bar');
 
331
    echo $request->getResource();
 
332
    // /get?baz=bar
 
333
 
 
334
Request Config
 
335
--------------
 
336
 
 
337
Request messages contain a configuration collection that can be used by
 
338
event listeners and HTTP adapters to modify how a request behaves or is
 
339
transferred over the wire. For example, many of the request options that are
 
340
specified when creating a request are actually set as config options that are
 
341
only acted upon by adapters and listeners when the request is sent.
 
342
 
 
343
You can get access to the request's config object using the ``getConfig()``
 
344
method of a request.
 
345
 
 
346
.. code-block:: php
 
347
 
 
348
    $request = $client->createRequest('GET', '/');
 
349
    $config = $request->getConfig();
 
350
 
 
351
The config object is a ``GuzzleHttp\Common\Collection`` object that acts like
 
352
an associative array. You can grab values from the collection using array like
 
353
access. You can also modify and remove values using array like access.
 
354
 
 
355
.. code-block:: php
 
356
 
 
357
    $config['foo'] = 'bar';
 
358
    echo $config['foo'];
 
359
    // bar
 
360
 
 
361
    var_export(isset($config['foo']));
 
362
    // true
 
363
 
 
364
    unset($config['foo']);
 
365
    var_export(isset($config['foo']));
 
366
    // false
 
367
 
 
368
    var_export($config['foo']);
 
369
    // NULL
 
370
 
 
371
HTTP adapters and event listeners can expose additional customization options
 
372
through request config settings. For example, in order to specify custom cURL
 
373
options to the cURL adapter, you need to specify an associative array in the
 
374
``curl`` ``config`` request option.
 
375
 
 
376
.. code-block:: php
 
377
 
 
378
    $client->get('/', [
 
379
        'config' => [
 
380
            'curl' => [
 
381
                CURLOPT_HTTPAUTH => CURLAUTH_NTLM,
 
382
                CURLOPT_USERPWD  => 'username:password'
 
383
            ]
 
384
        ]
 
385
    ]);
 
386
 
 
387
Consult the HTTP adapters and event listeners you are using to see if they
 
388
allow customization through request configuration options.
 
389
 
 
390
Event Emitter
 
391
-------------
 
392
 
 
393
Request objects implement ``GuzzleHttp\Common\HasEmitterInterface``, so they
 
394
have a method called ``getEmitter()`` that can be used to get an event emitter
 
395
used by the request. Any listener or subscriber attached to a request will only
 
396
be triggered for the lifecycle events of a specific request. Conversely, adding
 
397
an event listener or subscriber to a client will listen to all lifecycle events
 
398
of all requests created by the client.
 
399
 
 
400
See :doc:`events` for more information.
 
401
 
 
402
Responses
 
403
=========
 
404
 
 
405
Responses are the HTTP messages a client receives from a server after sending
 
406
an HTTP request message.
 
407
 
 
408
Start-Line
 
409
----------
 
410
 
 
411
The start-line of a response contains the protocol and protocol version,
 
412
status code, and reason phrase.
 
413
 
 
414
.. code-block:: php
 
415
 
 
416
    $response = GuzzleHttp\get('http://httpbin.org/get');
 
417
    echo $response->getStatusCode();
 
418
    // 200
 
419
    echo $response->getReasonPhrase();
 
420
    // OK
 
421
    echo $response->getProtocolVersion();
 
422
    // 1.1
 
423
 
 
424
Body
 
425
----
 
426
 
 
427
As described earlier, you can get the body of a response using the
 
428
``getBody()`` method.
 
429
 
 
430
.. code-block:: php
 
431
 
 
432
    if ($body = $response->getBody()) {
 
433
        echo $body;
 
434
        // Cast to a string: { ... }
 
435
        $body->seek(0);
 
436
        // Rewind the body
 
437
        $body->read(1024);
 
438
        // Read bytes of the body
 
439
    }
 
440
 
 
441
When working with JSON responses, you can use the ``json()`` method of a
 
442
response:
 
443
 
 
444
.. code-block:: php
 
445
 
 
446
    $json = $response->json();
 
447
 
 
448
.. note::
 
449
 
 
450
    Guzzle uses the ``json_decode()`` method of PHP and uses arrays rather than
 
451
    ``stdClass`` objects for objects.
 
452
 
 
453
You can use the ``xml()`` method when working with XML data.
 
454
 
 
455
.. code-block:: php
 
456
 
 
457
    $xml = $response->xml();
 
458
 
 
459
.. note::
 
460
 
 
461
    Guzzle uses the ``SimpleXMLElement`` objects when converting response
 
462
    bodies to XML.
 
463
 
 
464
Effective URL
 
465
-------------
 
466
 
 
467
The URL that was ultimately accessed that returned a response can be accessed
 
468
using the ``getEffectiveUrl()`` method of a response. This method will return
 
469
the URL of a request or the URL of the last redirected URL if any redirects
 
470
occurred while transferring a request.
 
471
 
 
472
.. code-block:: php
 
473
 
 
474
    $response = GuzzleHttp\get('http://httpbin.org/get');
 
475
    echo $response->getEffectiveUrl();
 
476
    // http://httpbin.org/get
 
477
 
 
478
    $response = GuzzleHttp\get('http://httpbin.org/redirect-to?url=http://www.google.com');
 
479
    echo $response->getEffectiveUrl();
 
480
    // http://www.google.com