quickstart.rst 19 KB

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