quickstart.rst 20 KB

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