PluginProbe
StockPack – Stock photos and AI images from Unsplash, Adobe Stock, Freepik and more / 2.4.2
StockPack – Stock photos and AI images from Unsplash, Adobe Stock, Freepik and more v2.4.2
3.7.2 3.7.1 3.7.0 3.6.0 3.6.1 3.5.2 trunk 2.0 2.1 2.2 2.3 2.4 2.4.1 2.4.2 2.4.3 2.5.0 2.5.1 2.5.2 2.5.3 2.5.4 2.5.5 2.5.6 2.5.7 2.6.0 2.6.1 All 73 releases
stockpack / vendor / guzzlehttp / guzzle / docs / quickstart.rst

quickstart.rst in StockPack – Stock photos and AI images from Unsplash, Adobe Stock, Freepik and more 2.4.2, at vendor/guzzlehttp/guzzle/docs/quickstart.rst

626 lines 20.1 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
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
10 Making a Request
11 ================
12
13 You can send requests with Guzzle using a ``GuzzleHttp\ClientInterface``
14 object.
15
16
17 Creating a Client
18 -----------------
19
20 .. code-block:: php
21
22 use GuzzleHttp\Client;
23
24 $client = new Client([
25 // Base URI is used with relative requests
26 'base_uri' => 'http://httpbin.org',
27 // You can set any number of default request options.
28 'timeout' => 2.0,
29 ]);
30
31 Clients are immutable in Guzzle 6, which means that you cannot change the defaults used by a client after it's created.
32
33 The client constructor accepts an associative array of options:
34
35 ``base_uri``
36 (string|UriInterface) Base URI of the client that is merged into relative
37 URIs. Can be a string or instance of UriInterface. When a relative URI
38 is provided to a client, the client will combine the base URI with the
39 relative URI using the rules described in
40 `RFC 3986, section 2 <http://tools.ietf.org/html/rfc3986#section-5.2>`_.
41
42 .. code-block:: php
43
44 // Create a client with a base URI
45 $client = new GuzzleHttp\Client(['base_uri' => 'https://foo.com/api/']);
46 // Send a request to https://foo.com/api/test
47 $response = $client->request('GET', 'test');
48 // Send a request to https://foo.com/root
49 $response = $client->request('GET', '/root');
50
51 Don't feel like reading RFC 3986? Here are some quick examples on how a
52 ``base_uri`` is resolved with another URI.
53
54 ======================= ================== ===============================
55 base_uri URI Result
56 ======================= ================== ===============================
57 ``http://foo.com`` ``/bar`` ``http://foo.com/bar``
58 ``http://foo.com/foo`` ``/bar`` ``http://foo.com/bar``
59 ``http://foo.com/foo`` ``bar`` ``http://foo.com/bar``
60 ``http://foo.com/foo/`` ``bar`` ``http://foo.com/foo/bar``
61 ``http://foo.com`` ``http://baz.com`` ``http://baz.com``
62 ``http://foo.com/?bar`` ``bar`` ``http://foo.com/bar``
63 ======================= ================== ===============================
64
65 ``handler``
66 (callable) Function that transfers HTTP requests over the wire. The
67 function is called with a ``Psr7\Http\Message\RequestInterface`` and array
68 of transfer options, and must return a
69 ``GuzzleHttp\Promise\PromiseInterface`` that is fulfilled with a
70 ``Psr7\Http\Message\ResponseInterface`` on success. ``handler`` is a
71 constructor only option that cannot be overridden in per/request options.
72
73 ``...``
74 (mixed) All other options passed to the constructor are used as default
75 request options with every request created by the client.
76
77
78 Sending Requests
79 ----------------
80
81 Magic methods on the client make it easy to send synchronous requests:
82
83 .. code-block:: php
84
85 $response = $client->get('http://httpbin.org/get');
86 $response = $client->delete('http://httpbin.org/delete');
87 $response = $client->head('http://httpbin.org/get');
88 $response = $client->options('http://httpbin.org/get');
89 $response = $client->patch('http://httpbin.org/patch');
90 $response = $client->post('http://httpbin.org/post');
91 $response = $client->put('http://httpbin.org/put');
92
93 You can create a request and then send the request with the client when you're
94 ready:
95
96 .. code-block:: php
97
98 use GuzzleHttp\Psr7\Request;
99
100 $request = new Request('PUT', 'http://httpbin.org/put');
101 $response = $client->send($request, ['timeout' => 2]);
102
103 Client objects provide a great deal of flexibility in how request are
104 transferred including default request options, default handler stack middleware
105 that are used by each request, and a base URI that allows you to send requests
106 with relative URIs.
107
108 You can find out more about client middleware in the
109 :doc:`handlers-and-middleware` page of the documentation.
110
111
112 Async Requests
113 --------------
114
115 You can send asynchronous requests using the magic methods provided by a client:
116
117 .. code-block:: php
118
119 $promise = $client->getAsync('http://httpbin.org/get');
120 $promise = $client->deleteAsync('http://httpbin.org/delete');
121 $promise = $client->headAsync('http://httpbin.org/get');
122 $promise = $client->optionsAsync('http://httpbin.org/get');
123 $promise = $client->patchAsync('http://httpbin.org/patch');
124 $promise = $client->postAsync('http://httpbin.org/post');
125 $promise = $client->putAsync('http://httpbin.org/put');
126
127 You can also use the `sendAsync()` and `requestAsync()` methods of a client:
128
129 .. code-block:: php
130
131 use GuzzleHttp\Psr7\Request;
132
133 // Create a PSR-7 request object to send
134 $headers = ['X-Foo' => 'Bar'];
135 $body = 'Hello!';
136 $request = new Request('HEAD', 'http://httpbin.org/head', $headers, $body);
137 $promise = $client->sendAsync($request);
138
139 // Or, if you don't need to pass in a request instance:
140 $promise = $client->requestAsync('GET', 'http://httpbin.org/get');
141
142 The promise returned by these methods implements the
143 `Promises/A+ spec <https://promisesaplus.com/>`_, provided by the
144 `Guzzle promises library <https://github.com/guzzle/promises>`_. This means
145 that you can chain ``then()`` calls off of the promise. These then calls are
146 either fulfilled with a successful ``Psr\Http\Message\ResponseInterface`` or
147 rejected with an exception.
148
149 .. code-block:: php
150
151 use Psr\Http\Message\ResponseInterface;
152 use GuzzleHttp\Exception\RequestException;
153
154 $promise = $client->requestAsync('GET', 'http://httpbin.org/get');
155 $promise->then(
156 function (ResponseInterface $res) {
157 echo $res->getStatusCode() . "\n";
158 },
159 function (RequestException $e) {
160 echo $e->getMessage() . "\n";
161 echo $e->getRequest()->getMethod();
162 }
163 );
164
165
166 Concurrent requests
167 -------------------
168
169 You can send multiple requests concurrently using promises and asynchronous
170 requests.
171
172 .. code-block:: php
173
174 use GuzzleHttp\Client;
175 use GuzzleHttp\Promise;
176
177 $client = new Client(['base_uri' => 'http://httpbin.org/']);
178
179 // Initiate each request but do not block
180 $promises = [
181 'image' => $client->getAsync('/image'),
182 'png' => $client->getAsync('/image/png'),
183 'jpeg' => $client->getAsync('/image/jpeg'),
184 'webp' => $client->getAsync('/image/webp')
185 ];
186
187 // Wait for the requests to complete; throws a ConnectException
188 // if any of the requests fail
189 $responses = Promise\unwrap($promises);
190
191 // Wait for the requests to complete, even if some of them fail
192 $responses = Promise\settle($promises)->wait();
193
194 // You can access each response using the key of the promise
195 echo $responses['image']->getHeader('Content-Length')[0];
196 echo $responses['png']->getHeader('Content-Length')[0];
197
198 You can use the ``GuzzleHttp\Pool`` object when you have an indeterminate
199 amount of requests you wish to send.
200
201 .. code-block:: php
202
203 use GuzzleHttp\Client;
204 use GuzzleHttp\Exception\RequestException;
205 use GuzzleHttp\Pool;
206 use GuzzleHttp\Psr7\Request;
207 use GuzzleHttp\Psr7\Response;
208
209 $client = new Client();
210
211 $requests = function ($total) {
212 $uri = 'http://127.0.0.1:8126/guzzle-server/perf';
213 for ($i = 0; $i < $total; $i++) {
214 yield new Request('GET', $uri);
215 }
216 };
217
218 $pool = new Pool($client, $requests(100), [
219 'concurrency' => 5,
220 'fulfilled' => function (Response $response, $index) {
221 // this is delivered each successful response
222 },
223 'rejected' => function (RequestException $reason, $index) {
224 // this is delivered each failed request
225 },
226 ]);
227
228 // Initiate the transfers and create a promise
229 $promise = $pool->promise();
230
231 // Force the pool of requests to complete.
232 $promise->wait();
233
234 Or using a closure that will return a promise once the pool calls the closure.
235
236 .. code-block:: php
237
238 $client = new Client();
239
240 $requests = function ($total) use ($client) {
241 $uri = 'http://127.0.0.1:8126/guzzle-server/perf';
242 for ($i = 0; $i < $total; $i++) {
243 yield function() use ($client, $uri) {
244 return $client->getAsync($uri);
245 };
246 }
247 };
248
249 $pool = new Pool($client, $requests(100));
250
251
252 Using Responses
253 ===============
254
255 In the previous examples, we retrieved a ``$response`` variable or we were
256 delivered a response from a promise. The response object implements a PSR-7
257 response, ``Psr\Http\Message\ResponseInterface``, and contains lots of
258 helpful information.
259
260 You can get the status code and reason phrase of the response:
261
262 .. code-block:: php
263
264 $code = $response->getStatusCode(); // 200
265 $reason = $response->getReasonPhrase(); // OK
266
267 You can retrieve headers from the response:
268
269 .. code-block:: php
270
271 // Check if a header exists.
272 if ($response->hasHeader('Content-Length')) {
273 echo "It exists";
274 }
275
276 // Get a header from the response.
277 echo $response->getHeader('Content-Length')[0];
278
279 // Get all of the response headers.
280 foreach ($response->getHeaders() as $name => $values) {
281 echo $name . ': ' . implode(', ', $values) . "\r\n";
282 }
283
284 The body of a response can be retrieved using the ``getBody`` method. The body
285 can be used as a string, cast to a string, or used as a stream like object.
286
287 .. code-block:: php
288
289 $body = $response->getBody();
290 // Implicitly cast the body to a string and echo it
291 echo $body;
292 // Explicitly cast the body to a string
293 $stringBody = (string) $body;
294 // Read 10 bytes from the body
295 $tenBytes = $body->read(10);
296 // Read the remaining contents of the body as a string
297 $remainingBytes = $body->getContents();
298
299
300 Query String Parameters
301 =======================
302
303 You can provide query string parameters with a request in several ways.
304
305 You can set query string parameters in the request's URI:
306
307 .. code-block:: php
308
309 $response = $client->request('GET', 'http://httpbin.org?foo=bar');
310
311 You can specify the query string parameters using the ``query`` request
312 option as an array.
313
314 .. code-block:: php
315
316 $client->request('GET', 'http://httpbin.org', [
317 'query' => ['foo' => 'bar']
318 ]);
319
320 Providing the option as an array will use PHP's ``http_build_query`` function
321 to format the query string.
322
323 And finally, you can provide the ``query`` request option as a string.
324
325 .. code-block:: php
326
327 $client->request('GET', 'http://httpbin.org', ['query' => 'foo=bar']);
328
329
330 Uploading Data
331 ==============
332
333 Guzzle provides several methods for uploading data.
334
335 You can send requests that contain a stream of data by passing a string,
336 resource returned from ``fopen``, or an instance of a
337 ``Psr\Http\Message\StreamInterface`` to the ``body`` request option.
338
339 .. code-block:: php
340
341 // Provide the body as a string.
342 $r = $client->request('POST', 'http://httpbin.org/post', [
343 'body' => 'raw data'
344 ]);
345
346 // Provide an fopen resource.
347 $body = fopen('/path/to/file', 'r');
348 $r = $client->request('POST', 'http://httpbin.org/post', ['body' => $body]);
349
350 // Use the stream_for() function to create a PSR-7 stream.
351 $body = \GuzzleHttp\Psr7\stream_for('hello!');
352 $r = $client->request('POST', 'http://httpbin.org/post', ['body' => $body]);
353
354 An easy way to upload JSON data and set the appropriate header is using the
355 ``json`` request option:
356
357 .. code-block:: php
358
359 $r = $client->request('PUT', 'http://httpbin.org/put', [
360 'json' => ['foo' => 'bar']
361 ]);
362
363
364 POST/Form Requests
365 ------------------
366
367 In addition to specifying the raw data of a request using the ``body`` request
368 option, Guzzle provides helpful abstractions over sending POST data.
369
370
371 Sending form fields
372 ~~~~~~~~~~~~~~~~~~~
373
374 Sending ``application/x-www-form-urlencoded`` POST requests requires that you
375 specify the POST fields as an array in the ``form_params`` request options.
376
377 .. code-block:: php
378
379 $response = $client->request('POST', 'http://httpbin.org/post', [
380 'form_params' => [
381 'field_name' => 'abc',
382 'other_field' => '123',
383 'nested_field' => [
384 'nested' => 'hello'
385 ]
386 ]
387 ]);
388
389
390 Sending form files
391 ~~~~~~~~~~~~~~~~~~
392
393 You can send files along with a form (``multipart/form-data`` POST requests),
394 using the ``multipart`` request option. ``multipart`` accepts an array of
395 associative arrays, where each associative array contains the following keys:
396
397 - name: (required, string) key mapping to the form field name.
398 - contents: (required, mixed) Provide a string to send the contents of the
399 file as a string, provide an fopen resource to stream the contents from a
400 PHP stream, or provide a ``Psr\Http\Message\StreamInterface`` to stream
401 the contents from a PSR-7 stream.
402
403 .. code-block:: php
404
405 $response = $client->request('POST', 'http://httpbin.org/post', [
406 'multipart' => [
407 [
408 'name' => 'field_name',
409 'contents' => 'abc'
410 ],
411 [
412 'name' => 'file_name',
413 'contents' => fopen('/path/to/file', 'r')
414 ],
415 [
416 'name' => 'other_file',
417 'contents' => 'hello',
418 'filename' => 'filename.txt',
419 'headers' => [
420 'X-Foo' => 'this is an extra header to include'
421 ]
422 ]
423 ]
424 ]);
425
426
427 Cookies
428 =======
429
430 Guzzle can maintain a cookie session for you if instructed using the
431 ``cookies`` request option. When sending a request, the ``cookies`` option
432 must be set to an instance of ``GuzzleHttp\Cookie\CookieJarInterface``.
433
434 .. code-block:: php
435
436 // Use a specific cookie jar
437 $jar = new \GuzzleHttp\Cookie\CookieJar;
438 $r = $client->request('GET', 'http://httpbin.org/cookies', [
439 'cookies' => $jar
440 ]);
441
442 You can set ``cookies`` to ``true`` in a client constructor if you would like
443 to use a shared cookie jar for all requests.
444
445 .. code-block:: php
446
447 // Use a shared client cookie jar
448 $client = new \GuzzleHttp\Client(['cookies' => true]);
449 $r = $client->request('GET', 'http://httpbin.org/cookies');
450
451 Different implementations exist for the ``GuzzleHttp\Cookie\CookieJarInterface``
452 :
453
454 - The ``GuzzleHttp\Cookie\CookieJar`` class stores cookies as an array.
455 - The ``GuzzleHttp\Cookie\FileCookieJar`` class persists non-session cookies
456 using a JSON formatted file.
457 - The ``GuzzleHttp\Cookie\SessionCookieJar`` class persists cookies in the
458 client session.
459
460 You can manually set cookies into a cookie jar with the named constructor
461 ``fromArray(array $cookies, $domain)``.
462
463 .. code-block:: php
464
465 $jar = \GuzzleHttp\Cookie\CookieJar::fromArray(
466 [
467 'some_cookie' => 'foo',
468 'other_cookie' => 'barbaz1234'
469 ],
470 'example.org'
471 );
472
473 You can get a cookie by its name with the ``getCookieByName($name)`` method
474 which returns a ``GuzzleHttp\Cookie\SetCookie`` instance.
475
476 .. code-block:: php
477
478 $cookie = $jar->getCookieByName('some_cookie');
479
480 $cookie->getValue(); // 'foo'
481 $cookie->getDomain(); // 'example.org'
482 $cookie->getExpires(); // expiration date as a Unix timestamp
483
484 The cookies can be also fetched into an array thanks to the `toArray()` method.
485 The ``GuzzleHttp\Cookie\CookieJarInterface`` interface extends
486 ``Traversable`` so it can be iterated in a foreach loop.
487
488
489 Redirects
490 =========
491
492 Guzzle will automatically follow redirects unless you tell it not to. You can
493 customize the redirect behavior using the ``allow_redirects`` request option.
494
495 - Set to ``true`` to enable normal redirects with a maximum number of 5
496 redirects. This is the default setting.
497 - Set to ``false`` to disable redirects.
498 - Pass an associative array containing the 'max' key to specify the maximum
499 number of redirects and optionally provide a 'strict' key value to specify
500 whether or not to use strict RFC compliant redirects (meaning redirect POST
501 requests with POST requests vs. doing what most browsers do which is
502 redirect POST requests with GET requests).
503
504 .. code-block:: php
505
506 $response = $client->request('GET', 'http://github.com');
507 echo $response->getStatusCode();
508 // 200
509
510 The following example shows that redirects can be disabled.
511
512 .. code-block:: php
513
514 $response = $client->request('GET', 'http://github.com', [
515 'allow_redirects' => false
516 ]);
517 echo $response->getStatusCode();
518 // 301
519
520
521 Exceptions
522 ==========
523
524 **Tree View**
525
526 The following tree view describes how the Guzzle Exceptions depend
527 on each other.
528
529 .. code-block:: none
530
531 . \RuntimeException
532 ├── SeekException (implements GuzzleException)
533 └── TransferException (implements GuzzleException)
534 └── RequestException
535 ├── BadResponseException
536 │   ├── ServerException
537 │ └── ClientException
538 ├── ConnectException
539 └── TooManyRedirectsException
540
541 Guzzle throws exceptions for errors that occur during a transfer.
542
543 - In the event of a networking error (connection timeout, DNS errors, etc.),
544 a ``GuzzleHttp\Exception\RequestException`` is thrown. This exception
545 extends from ``GuzzleHttp\Exception\TransferException``. Catching this
546 exception will catch any exception that can be thrown while transferring
547 requests.
548
549 .. code-block:: php
550
551 use GuzzleHttp\Psr7;
552 use GuzzleHttp\Exception\RequestException;
553
554 try {
555 $client->request('GET', 'https://github.com/_abc_123_404');
556 } catch (RequestException $e) {
557 echo Psr7\str($e->getRequest());
558 if ($e->hasResponse()) {
559 echo Psr7\str($e->getResponse());
560 }
561 }
562
563 - A ``GuzzleHttp\Exception\ConnectException`` exception is thrown in the
564 event of a networking error. This exception extends from
565 ``GuzzleHttp\Exception\RequestException``.
566
567 - A ``GuzzleHttp\Exception\ClientException`` is thrown for 400
568 level errors if the ``http_errors`` request option is set to true. This
569 exception extends from ``GuzzleHttp\Exception\BadResponseException`` and
570 ``GuzzleHttp\Exception\BadResponseException`` extends from
571 ``GuzzleHttp\Exception\RequestException``.
572
573 .. code-block:: php
574
575 use GuzzleHttp\Psr7;
576 use GuzzleHttp\Exception\ClientException;
577
578 try {
579 $client->request('GET', 'https://github.com/_abc_123_404');
580 } catch (ClientException $e) {
581 echo Psr7\str($e->getRequest());
582 echo Psr7\str($e->getResponse());
583 }
584
585 - A ``GuzzleHttp\Exception\ServerException`` is thrown for 500 level
586 errors if the ``http_errors`` request option is set to true. This
587 exception extends from ``GuzzleHttp\Exception\BadResponseException``.
588
589 - A ``GuzzleHttp\Exception\TooManyRedirectsException`` is thrown when too
590 many redirects are followed. This exception extends from ``GuzzleHttp\Exception\RequestException``.
591
592 All of the above exceptions extend from
593 ``GuzzleHttp\Exception\TransferException``.
594
595
596 Environment Variables
597 =====================
598
599 Guzzle exposes a few environment variables that can be used to customize the
600 behavior of the library.
601
602 ``GUZZLE_CURL_SELECT_TIMEOUT``
603 Controls the duration in seconds that a curl_multi_* handler will use when
604 selecting on curl handles using ``curl_multi_select()``. Some systems
605 have issues with PHP's implementation of ``curl_multi_select()`` where
606 calling this function always results in waiting for the maximum duration of
607 the timeout.
608 ``HTTP_PROXY``
609 Defines the proxy to use when sending requests using the "http" protocol.
610
611 Note: because the HTTP_PROXY variable may contain arbitrary user input on some (CGI) environments, the variable is only used on the CLI SAPI. See https://httpoxy.org for more information.
612 ``HTTPS_PROXY``
613 Defines the proxy to use when sending requests using the "https" protocol.
614 ``NO_PROXY``
615 Defines URLs for which a proxy should not be used. See :ref:`proxy-option` for usage.
616
617
618 Relevant ini Settings
619 ---------------------
620
621 Guzzle can utilize PHP ini settings when configuring clients.
622
623 ``openssl.cafile``
624 Specifies the path on disk to a CA file in PEM format to use when sending
625 requests over "https". See: https://wiki.php.net/rfc/tls-peer-verification#phpini_defaults
626