quickstart.rst 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625
  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 6, 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 2 <http://tools.ietf.org/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`` ``http://baz.com`` ``http://baz.com``
  46. ``http://foo.com/?bar`` ``bar`` ``http://foo.com/bar``
  47. ======================= ================== ===============================
  48. ``handler``
  49. (callable) Function that transfers HTTP requests over the wire. The
  50. function is called with a ``Psr7\Http\Message\RequestInterface`` and array
  51. of transfer options, and must return a
  52. ``GuzzleHttp\Promise\PromiseInterface`` that is fulfilled with a
  53. ``Psr7\Http\Message\ResponseInterface`` on success. ``handler`` is a
  54. constructor only option that cannot be overridden in per/request options.
  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\unwrap($promises);
  139. // Wait for the requests to complete, even if some of them fail
  140. $responses = Promise\settle($promises)->wait();
  141. // You can access each response using the key of the promise
  142. echo $responses['image']->getHeader('Content-Length')[0]
  143. echo $responses['png']->getHeader('Content-Length')[0]
  144. You can use the ``GuzzleHttp\Pool`` object when you have an indeterminate
  145. amount of requests you wish to send.
  146. .. code-block:: php
  147. use GuzzleHttp\Client;
  148. use GuzzleHttp\Exception\RequestException;
  149. use GuzzleHttp\Pool;
  150. use GuzzleHttp\Psr7\Request;
  151. use GuzzleHttp\Psr7\Response;
  152. $client = new Client();
  153. $requests = function ($total) {
  154. $uri = 'http://127.0.0.1:8126/guzzle-server/perf';
  155. for ($i = 0; $i < $total; $i++) {
  156. yield new Request('GET', $uri);
  157. }
  158. };
  159. $pool = new Pool($client, $requests(100), [
  160. 'concurrency' => 5,
  161. 'fulfilled' => function (Response $response, $index) {
  162. // this is delivered each successful response
  163. },
  164. 'rejected' => function (RequestException $reason, $index) {
  165. // this is delivered each failed request
  166. },
  167. ]);
  168. // Initiate the transfers and create a promise
  169. $promise = $pool->promise();
  170. // Force the pool of requests to complete.
  171. $promise->wait();
  172. Or using a closure that will return a promise once the pool calls the closure.
  173. .. code-block:: php
  174. $client = new Client();
  175. $requests = function ($total) use ($client) {
  176. $uri = 'http://127.0.0.1:8126/guzzle-server/perf';
  177. for ($i = 0; $i < $total; $i++) {
  178. yield function() use ($client, $uri) {
  179. return $client->getAsync($uri);
  180. };
  181. }
  182. };
  183. $pool = new Pool($client, $requests(100));
  184. Using Responses
  185. ===============
  186. In the previous examples, we retrieved a ``$response`` variable or we were
  187. delivered a response from a promise. The response object implements a PSR-7
  188. response, ``Psr\Http\Message\ResponseInterface``, and contains lots of
  189. helpful information.
  190. You can get the status code and reason phrase of the response:
  191. .. code-block:: php
  192. $code = $response->getStatusCode(); // 200
  193. $reason = $response->getReasonPhrase(); // OK
  194. You can retrieve headers from the response:
  195. .. code-block:: php
  196. // Check if a header exists.
  197. if ($response->hasHeader('Content-Length')) {
  198. echo "It exists";
  199. }
  200. // Get a header from the response.
  201. echo $response->getHeader('Content-Length')[0];
  202. // Get all of the response headers.
  203. foreach ($response->getHeaders() as $name => $values) {
  204. echo $name . ': ' . implode(', ', $values) . "\r\n";
  205. }
  206. The body of a response can be retrieved using the ``getBody`` method. The body
  207. can be used as a string, cast to a string, or used as a stream like object.
  208. .. code-block:: php
  209. $body = $response->getBody();
  210. // Implicitly cast the body to a string and echo it
  211. echo $body;
  212. // Explicitly cast the body to a string
  213. $stringBody = (string) $body;
  214. // Read 10 bytes from the body
  215. $tenBytes = $body->read(10);
  216. // Read the remaining contents of the body as a string
  217. $remainingBytes = $body->getContents();
  218. Query String Parameters
  219. =======================
  220. You can provide query string parameters with a request in several ways.
  221. You can set query string parameters in the request's URI:
  222. .. code-block:: php
  223. $response = $client->request('GET', 'http://httpbin.org?foo=bar');
  224. You can specify the query string parameters using the ``query`` request
  225. option as an array.
  226. .. code-block:: php
  227. $client->request('GET', 'http://httpbin.org', [
  228. 'query' => ['foo' => 'bar']
  229. ]);
  230. Providing the option as an array will use PHP's ``http_build_query`` function
  231. to format the query string.
  232. And finally, you can provide the ``query`` request option as a string.
  233. .. code-block:: php
  234. $client->request('GET', 'http://httpbin.org', ['query' => 'foo=bar']);
  235. Uploading Data
  236. ==============
  237. Guzzle provides several methods for uploading data.
  238. You can send requests that contain a stream of data by passing a string,
  239. resource returned from ``fopen``, or an instance of a
  240. ``Psr\Http\Message\StreamInterface`` to the ``body`` request option.
  241. .. code-block:: php
  242. // Provide the body as a string.
  243. $r = $client->request('POST', 'http://httpbin.org/post', [
  244. 'body' => 'raw data'
  245. ]);
  246. // Provide an fopen resource.
  247. $body = fopen('/path/to/file', 'r');
  248. $r = $client->request('POST', 'http://httpbin.org/post', ['body' => $body]);
  249. // Use the stream_for() function to create a PSR-7 stream.
  250. $body = \GuzzleHttp\Psr7\stream_for('hello!');
  251. $r = $client->request('POST', 'http://httpbin.org/post', ['body' => $body]);
  252. An easy way to upload JSON data and set the appropriate header is using the
  253. ``json`` request option:
  254. .. code-block:: php
  255. $r = $client->request('PUT', 'http://httpbin.org/put', [
  256. 'json' => ['foo' => 'bar']
  257. ]);
  258. POST/Form Requests
  259. ------------------
  260. In addition to specifying the raw data of a request using the ``body`` request
  261. option, Guzzle provides helpful abstractions over sending POST data.
  262. Sending form fields
  263. ~~~~~~~~~~~~~~~~~~~
  264. Sending ``application/x-www-form-urlencoded`` POST requests requires that you
  265. specify the POST fields as an array in the ``form_params`` request options.
  266. .. code-block:: php
  267. $response = $client->request('POST', 'http://httpbin.org/post', [
  268. 'form_params' => [
  269. 'field_name' => 'abc',
  270. 'other_field' => '123',
  271. 'nested_field' => [
  272. 'nested' => 'hello'
  273. ]
  274. ]
  275. ]);
  276. Sending form files
  277. ~~~~~~~~~~~~~~~~~~
  278. You can send files along with a form (``multipart/form-data`` POST requests),
  279. using the ``multipart`` request option. ``multipart`` accepts an array of
  280. associative arrays, where each associative array contains the following keys:
  281. - name: (required, string) key mapping to the form field name.
  282. - contents: (required, mixed) Provide a string to send the contents of the
  283. file as a string, provide an fopen resource to stream the contents from a
  284. PHP stream, or provide a ``Psr\Http\Message\StreamInterface`` to stream
  285. the contents from a PSR-7 stream.
  286. .. code-block:: php
  287. $response = $client->request('POST', 'http://httpbin.org/post', [
  288. 'multipart' => [
  289. [
  290. 'name' => 'field_name',
  291. 'contents' => 'abc'
  292. ],
  293. [
  294. 'name' => 'file_name',
  295. 'contents' => fopen('/path/to/file', 'r')
  296. ],
  297. [
  298. 'name' => 'other_file',
  299. 'contents' => 'hello',
  300. 'filename' => 'filename.txt',
  301. 'headers' => [
  302. 'X-Foo' => 'this is an extra header to include'
  303. ]
  304. ]
  305. ]
  306. ]);
  307. Cookies
  308. =======
  309. Guzzle can maintain a cookie session for you if instructed using the
  310. ``cookies`` request option. When sending a request, the ``cookies`` option
  311. must be set to an instance of ``GuzzleHttp\Cookie\CookieJarInterface``.
  312. .. code-block:: php
  313. // Use a specific cookie jar
  314. $jar = new \GuzzleHttp\Cookie\CookieJar;
  315. $r = $client->request('GET', 'http://httpbin.org/cookies', [
  316. 'cookies' => $jar
  317. ]);
  318. You can set ``cookies`` to ``true`` in a client constructor if you would like
  319. to use a shared cookie jar for all requests.
  320. .. code-block:: php
  321. // Use a shared client cookie jar
  322. $client = new \GuzzleHttp\Client(['cookies' => true]);
  323. $r = $client->request('GET', 'http://httpbin.org/cookies');
  324. Different implementations exist for the ``GuzzleHttp\Cookie\CookieJarInterface``
  325. :
  326. - The ``GuzzleHttp\Cookie\CookieJar`` class stores cookies as an array.
  327. - The ``GuzzleHttp\Cookie\FileCookieJar`` class persists non-session cookies
  328. using a JSON formatted file.
  329. - The ``GuzzleHttp\Cookie\SessionCookieJar`` class persists cookies in the
  330. client session.
  331. You can manually set cookies into a cookie jar with the named constructor
  332. ``fromArray(array $cookies, $domain)``.
  333. .. code-block:: php
  334. $jar = \GuzzleHttp\Cookie\CookieJar::fromArray(
  335. [
  336. 'some_cookie' => 'foo',
  337. 'other_cookie' => 'barbaz1234'
  338. ],
  339. 'example.org'
  340. );
  341. You can get a cookie by its name with the ``getCookieByName($name)`` method
  342. which returns a ``GuzzleHttp\Cookie\SetCookie`` instance.
  343. .. code-block:: php
  344. $cookie = $jar->getCookieByName('some_cookie');
  345. $cookie->getValue(); // 'foo'
  346. $cookie->getDomain(); // 'example.org'
  347. $cookie->getExpires(); // expiration date as a Unix timestamp
  348. The cookies can be also fetched into an array thanks to the `toArray()` method.
  349. The ``GuzzleHttp\Cookie\CookieJarInterface`` interface extends
  350. ``Traversable`` so it can be iterated in a foreach loop.
  351. Redirects
  352. =========
  353. Guzzle will automatically follow redirects unless you tell it not to. You can
  354. customize the redirect behavior using the ``allow_redirects`` request option.
  355. - Set to ``true`` to enable normal redirects with a maximum number of 5
  356. redirects. This is the default setting.
  357. - Set to ``false`` to disable redirects.
  358. - Pass an associative array containing the 'max' key to specify the maximum
  359. number of redirects and optionally provide a 'strict' key value to specify
  360. whether or not to use strict RFC compliant redirects (meaning redirect POST
  361. requests with POST requests vs. doing what most browsers do which is
  362. redirect POST requests with GET requests).
  363. .. code-block:: php
  364. $response = $client->request('GET', 'http://github.com');
  365. echo $response->getStatusCode();
  366. // 200
  367. The following example shows that redirects can be disabled.
  368. .. code-block:: php
  369. $response = $client->request('GET', 'http://github.com', [
  370. 'allow_redirects' => false
  371. ]);
  372. echo $response->getStatusCode();
  373. // 301
  374. Exceptions
  375. ==========
  376. **Tree View**
  377. The following tree view describes how the Guzzle Exceptions depend
  378. on each other.
  379. .. code-block:: none
  380. . \RuntimeException
  381. ├── SeekException (implements GuzzleException)
  382. └── TransferException (implements GuzzleException)
  383. └── RequestException
  384. ├── BadResponseException
  385. │   ├── ServerException
  386. │ └── ClientException
  387. ├── ConnectException
  388. └── TooManyRedirectsException
  389. Guzzle throws exceptions for errors that occur during a transfer.
  390. - In the event of a networking error (connection timeout, DNS errors, etc.),
  391. a ``GuzzleHttp\Exception\RequestException`` is thrown. This exception
  392. extends from ``GuzzleHttp\Exception\TransferException``. Catching this
  393. exception will catch any exception that can be thrown while transferring
  394. requests.
  395. .. code-block:: php
  396. use GuzzleHttp\Psr7;
  397. use GuzzleHttp\Exception\RequestException;
  398. try {
  399. $client->request('GET', 'https://github.com/_abc_123_404');
  400. } catch (RequestException $e) {
  401. echo Psr7\str($e->getRequest());
  402. if ($e->hasResponse()) {
  403. echo Psr7\str($e->getResponse());
  404. }
  405. }
  406. - A ``GuzzleHttp\Exception\ConnectException`` exception is thrown in the
  407. event of a networking error. This exception extends from
  408. ``GuzzleHttp\Exception\RequestException``.
  409. - A ``GuzzleHttp\Exception\ClientException`` is thrown for 400
  410. level errors if the ``http_errors`` request option is set to true. This
  411. exception extends from ``GuzzleHttp\Exception\BadResponseException`` and
  412. ``GuzzleHttp\Exception\BadResponseException`` extends from
  413. ``GuzzleHttp\Exception\RequestException``.
  414. .. code-block:: php
  415. use GuzzleHttp\Psr7;
  416. use GuzzleHttp\Exception\ClientException;
  417. try {
  418. $client->request('GET', 'https://github.com/_abc_123_404');
  419. } catch (ClientException $e) {
  420. echo Psr7\str($e->getRequest());
  421. echo Psr7\str($e->getResponse());
  422. }
  423. - A ``GuzzleHttp\Exception\ServerException`` is thrown for 500 level
  424. errors if the ``http_errors`` request option is set to true. This
  425. exception extends from ``GuzzleHttp\Exception\BadResponseException``.
  426. - A ``GuzzleHttp\Exception\TooManyRedirectsException`` is thrown when too
  427. many redirects are followed. This exception extends from ``GuzzleHttp\Exception\RequestException``.
  428. All of the above exceptions extend from
  429. ``GuzzleHttp\Exception\TransferException``.
  430. Environment Variables
  431. =====================
  432. Guzzle exposes a few environment variables that can be used to customize the
  433. behavior of the library.
  434. ``GUZZLE_CURL_SELECT_TIMEOUT``
  435. Controls the duration in seconds that a curl_multi_* handler will use when
  436. selecting on curl handles using ``curl_multi_select()``. Some systems
  437. have issues with PHP's implementation of ``curl_multi_select()`` where
  438. calling this function always results in waiting for the maximum duration of
  439. the timeout.
  440. ``HTTP_PROXY``
  441. Defines the proxy to use when sending requests using the "http" protocol.
  442. 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.
  443. ``HTTPS_PROXY``
  444. Defines the proxy to use when sending requests using the "https" protocol.
  445. ``NO_PROXY``
  446. Defines URLs for which a proxy should not be used. See :ref:`proxy-option` for usage.
  447. Relevant ini Settings
  448. ---------------------
  449. Guzzle can utilize PHP ini settings when configuring clients.
  450. ``openssl.cafile``
  451. Specifies the path on disk to a CA file in PEM format to use when sending
  452. requests over "https". See: https://wiki.php.net/rfc/tls-peer-verification#phpini_defaults