~tcuthbert/wordpress/openstack-objectstorage

« back to all changes in this revision

Viewing changes to vendor/guzzlehttp/guzzle/docs/quickstart.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
Quickstart
 
3
==========
 
4
 
 
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`
 
7
page.
 
8
 
 
9
Make a Request
 
10
==============
 
11
 
 
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.
 
17
 
 
18
Procedural API
 
19
--------------
 
20
 
 
21
Here's an example of sending a ``POST`` request using the procedural API.
 
22
 
 
23
.. code-block:: php
 
24
 
 
25
    $response = GuzzleHttp\post('http://httpbin.org/post', [
 
26
        'headers' => ['X-Foo' => 'Bar'],
 
27
        'body'    => ['field_name' => 'value']
 
28
    ]);
 
29
 
 
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.
 
32
 
 
33
.. code-block:: php
 
34
 
 
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');
 
40
 
 
41
Creating a Client
 
42
-----------------
 
43
 
 
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.
 
47
 
 
48
.. code-block:: php
 
49
 
 
50
    use GuzzleHttp\Client;
 
51
 
 
52
    $client = new Client();
 
53
    $response = $client->get('http://httpbin.org/get');
 
54
 
 
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');
 
62
 
 
63
You can create a request with a client and then send the request with the
 
64
client when you're ready.
 
65
 
 
66
.. code-block:: php
 
67
 
 
68
    $request = $client->createRequest('GET', 'http://www.foo.com');
 
69
    $response = $client->send($request);
 
70
 
 
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
 
75
documentation.
 
76
 
 
77
Using Responses
 
78
===============
 
79
 
 
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.
 
83
 
 
84
You can get the status code and reason phrase of the response.
 
85
 
 
86
.. code-block:: php
 
87
 
 
88
    $code = $response->getStatusCode();
 
89
    // 200
 
90
 
 
91
    $reason = $response->getReasonPhrase();
 
92
    // OK
 
93
 
 
94
Response Body
 
95
-------------
 
96
 
 
97
The body of a response can be retrieved and cast to a string.
 
98
 
 
99
.. code-block:: php
 
100
 
 
101
    $body = $response->getBody();
 
102
    echo $body;
 
103
    // { "some_json_data" ...}
 
104
 
 
105
You can also read read bytes from body of a response like a stream.
 
106
 
 
107
.. code-block:: php
 
108
 
 
109
    $body = $response->getBody();
 
110
 
 
111
    while (!$body->eof()) {
 
112
        echo $body->read(1024);
 
113
    }
 
114
 
 
115
JSON Responses
 
116
~~~~~~~~~~~~~~
 
117
 
 
118
You can more easily work with JSON responses using the ``json()`` method of a
 
119
response.
 
120
 
 
121
.. code-block:: php
 
122
 
 
123
    $response = $client->get('http://httpbin.org/get');
 
124
    $json = $response->json();
 
125
    var_dump($json[0]['origin']);
 
126
 
 
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.
 
130
 
 
131
XML Responses
 
132
~~~~~~~~~~~~~
 
133
 
 
134
You can use a response's ``xml()`` method to more easily work with responses
 
135
that contain XML data.
 
136
 
 
137
.. code-block:: php
 
138
 
 
139
    $response = $client->get('https://github.com/mtdowling.atom');
 
140
    $xml = $response->xml();
 
141
    echo $xml->id;
 
142
    // tag:github.com,2008:/mtdowling
 
143
 
 
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.
 
147
 
 
148
Query String Parameters
 
149
=======================
 
150
 
 
151
Sending query string parameters with a request is easy. You can set query
 
152
string parameters in the request's URL.
 
153
 
 
154
.. code-block:: php
 
155
 
 
156
    $response = $client->get('http://httpbin.org?foo=bar');
 
157
 
 
158
You can also specify the query string parameters using the ``query`` request
 
159
option.
 
160
 
 
161
.. code-block:: php
 
162
 
 
163
    $client->get('http://httpbin.org', [
 
164
        'query' => ['foo' => 'bar']
 
165
    ]);
 
166
 
 
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.
 
170
 
 
171
.. code-block:: php
 
172
 
 
173
    $request = $client->createRequest('GET', 'http://httpbin.org');
 
174
    $query = $request->getQuery();
 
175
    $query->set('foo', 'bar');
 
176
 
 
177
    // You can use the query string object like an array
 
178
    $query['baz'] = 'bam';
 
179
 
 
180
    // The query object can be cast to a string
 
181
    echo $query;
 
182
    // foo=bar&baz=bam
 
183
 
 
184
    // Setting a value to false or null will cause the "=" sign to be omitted
 
185
    $query['empty'] = null;
 
186
    echo $query;
 
187
    // foo=bar&baz=bam&empty
 
188
 
 
189
    // Use an empty string to include the "=" sign with an empty value
 
190
    $query['empty'] = '';
 
191
    echo $query;
 
192
    // foo=bar&baz=bam&empty=
 
193
 
 
194
.. _headers:
 
195
 
 
196
Request and Response Headers
 
197
----------------------------
 
198
 
 
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.
 
202
 
 
203
.. code-block:: php
 
204
 
 
205
    $response = $client->get('http://httpbin.org/get', [
 
206
        'headers' => ['X-Foo-Header' => 'value']
 
207
    ]);
 
208
 
 
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
 
211
object.
 
212
 
 
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.
 
216
 
 
217
.. code-block:: php
 
218
 
 
219
    $response = $client->get('http://www.yahoo.com');
 
220
    $length = $response->getHeader('Content-Length');
 
221
 
 
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.
 
227
 
 
228
.. code-block:: php
 
229
 
 
230
    $values = $response->getHeader('Set-Cookie', true);
 
231
    foreach ($values as $value) {
 
232
        echo $value;
 
233
    }
 
234
 
 
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.
 
238
 
 
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.
 
243
 
 
244
.. code-block:: php
 
245
 
 
246
    $headers = $response->getHeaders();
 
247
    foreach ($message->getHeaders() as $name => $values) {
 
248
        echo $name . ": " . implode(", ", $values);
 
249
    }
 
250
 
 
251
Modifying headers
 
252
-----------------
 
253
 
 
254
The headers of a message can be modified using the ``setHeader()``,
 
255
``addHeader()``, ``setHeaders()``, and ``removeHeader()`` methods of a request
 
256
or response object.
 
257
 
 
258
.. code-block:: php
 
259
 
 
260
    $request = $client->createRequest('GET', 'http://httpbin.org/get');
 
261
 
 
262
    // Set a single value for a header
 
263
    $request->setHeader('User-Agent', 'Testing!');
 
264
 
 
265
    // Set multiple values for a header in one call
 
266
    $request->setHeader('X-Foo', ['Baz', 'Bar']);
 
267
 
 
268
    // Add a header to the message
 
269
    $request->addHeader('X-Foo', 'Bam');
 
270
 
 
271
    echo $request->getHeader('X-Foo');
 
272
    // Baz, Bar, Bam
 
273
 
 
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: ''
 
278
 
 
279
Uploading Data
 
280
==============
 
281
 
 
282
Guzzle provides several methods of uploading data.
 
283
 
 
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.
 
287
 
 
288
.. code-block:: php
 
289
 
 
290
    $r = $client->post('http://httpbin.org/post', ['body' => 'raw data']);
 
291
 
 
292
You can easily upload JSON data using the ``json`` request option.
 
293
 
 
294
.. code-block:: php
 
295
 
 
296
    $r = $client->put('http://httpbin.org/put', ['json' => ['foo' => 'bar']]);
 
297
 
 
298
POST Requests
 
299
-------------
 
300
 
 
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.
 
303
 
 
304
Sending POST Fields
 
305
~~~~~~~~~~~~~~~~~~~
 
306
 
 
307
Sending ``application/x-www-form-urlencoded`` POST requests requires that you
 
308
specify the body of a POST request as an array.
 
309
 
 
310
.. code-block:: php
 
311
 
 
312
    $response = $client->post('http://httpbin.org/post', [
 
313
        'body' => [
 
314
            'field_name' => 'abc',
 
315
            'other_field' => '123'
 
316
        ]
 
317
    ]);
 
318
 
 
319
You can also build up POST requests before sending them.
 
320
 
 
321
.. code-block:: php
 
322
 
 
323
    $request = $client->createRequest('POST', 'http://httpbin.org/post');
 
324
    $postBody = $request->getBody();
 
325
 
 
326
    // $postBody is an instance of GuzzleHttp\Post\PostBodyInterface
 
327
    $postBody->setField('foo', 'bar');
 
328
    echo $postBody->getField('foo');
 
329
    // 'bar'
 
330
 
 
331
    echo json_encode($postBody->getFields());
 
332
    // {"foo": "bar"}
 
333
 
 
334
    // Send the POST request
 
335
    $response = $client->send($request);
 
336
 
 
337
Sending POST Files
 
338
~~~~~~~~~~~~~~~~~~
 
339
 
 
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.
 
345
 
 
346
.. code-block:: php
 
347
 
 
348
    use GuzzleHttp\Post\PostFile;
 
349
 
 
350
    $response = $client->post('http://httpbin.org/post', [
 
351
        'body' => [
 
352
            'field_name' => 'abc',
 
353
            'file_filed' => fopen('/path/to/file', 'r'),
 
354
            'other_file' => new PostFile('other_file', 'this is the content')
 
355
        ]
 
356
    ]);
 
357
 
 
358
Just like when sending POST fields, you can also build up POST requests with
 
359
files before sending them.
 
360
 
 
361
.. code-block:: php
 
362
 
 
363
    use GuzzleHttp\Post\PostFile;
 
364
 
 
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);
 
370
 
 
371
Cookies
 
372
=======
 
373
 
 
374
Guzzle can maintain a cookie session for you if instructed using the
 
375
``cookies`` request option.
 
376
 
 
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.
 
382
 
 
383
Redirects
 
384
=========
 
385
 
 
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.
 
388
 
 
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).
 
397
 
 
398
.. code-block:: php
 
399
 
 
400
    $response = $client->get('http://github.com');
 
401
    echo $response->getStatusCode();
 
402
    // 200
 
403
    echo $response->getEffectiveUrl();
 
404
    // 'https://github.com/'
 
405
 
 
406
The following example shows that redirects can be disabled.
 
407
 
 
408
.. code-block:: php
 
409
 
 
410
    $response = $client->get('http://github.com', ['allow_redirects' => false]);
 
411
    echo $response->getStatusCode();
 
412
    // 301
 
413
    echo $response->getEffectiveUrl();
 
414
    // 'http://github.com/'
 
415
 
 
416
Exceptions
 
417
==========
 
418
 
 
419
Guzzle throws exceptions for errors that occur during a transfer.
 
420
 
 
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.
 
426
 
 
427
  .. code-block:: php
 
428
 
 
429
      use GuzzleHttp\Exception\RequestException;
 
430
 
 
431
      try {
 
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();
 
437
          }
 
438
      }
 
439
 
 
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``.
 
445
 
 
446
  .. code-block:: php
 
447
 
 
448
      use GuzzleHttp\Exception\ClientException;
 
449
 
 
450
      try {
 
451
          $client->get('https://github.com/_abc_123_404');
 
452
      } catch (ClientException $e) {
 
453
          echo $e->getRequest();
 
454
          echo $e->getResponse();
 
455
      }
 
456
 
 
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.
 
465
 
 
466
All of the above exceptions extend from
 
467
``GuzzleHttp\Exception\TransferException``.