client.rst 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  1. ======================
  2. The Guzzle HTTP client
  3. ======================
  4. Guzzle gives PHP developers complete control over HTTP requests while utilizing HTTP/1.1 best practices. Guzzle's HTTP
  5. functionality is a robust framework built on top of the `PHP libcurl bindings <http://www.php.net/curl>`_.
  6. The three main parts of the Guzzle HTTP client are:
  7. +--------------+-------------------------------------------------------------------------------------------------------+
  8. | Clients | ``Guzzle\Http\Client`` (creates and sends requests, associates a response with a request) |
  9. +--------------+-------------------------------------------------------------------------------------------------------+
  10. | Requests | ``Guzzle\Http\Message\Request`` (requests with no body), |
  11. | | ``Guzzle\Http\Message\EntityEnclosingRequest`` (requests with a body) |
  12. +--------------+-------------------------------------------------------------------------------------------------------+
  13. | Responses | ``Guzzle\Http\Message\Response`` |
  14. +--------------+-------------------------------------------------------------------------------------------------------+
  15. Creating a Client
  16. -----------------
  17. Clients create requests, send requests, and set responses on a request object. When instantiating a client object,
  18. you can pass an optional "base URL" and optional array of configuration options. A base URL is a
  19. :doc:`URI template <uri-templates>` that contains the URL of a remote server. When creating requests with a relative
  20. URL, the base URL of a client will be merged into the request's URL.
  21. .. code-block:: php
  22. use Guzzle\Http\Client;
  23. // Create a client and provide a base URL
  24. $client = new Client('https://api.github.com');
  25. $request = $client->get('/user');
  26. $request->setAuth('user', 'pass');
  27. echo $request->getUrl();
  28. // >>> https://api.github.com/user
  29. // You must send a request in order for the transfer to occur
  30. $response = $request->send();
  31. echo $response->getBody();
  32. // >>> {"type":"User", ...
  33. echo $response->getHeader('Content-Length');
  34. // >>> 792
  35. $data = $response->json();
  36. echo $data['type'];
  37. // >>> User
  38. Base URLs
  39. ~~~~~~~~~
  40. Notice that the URL provided to the client's ``get()`` method is relative. Relative URLs will always merge into the
  41. base URL of the client. There are a few rules that control how the URLs are merged.
  42. .. tip::
  43. Guzzle follows `RFC 3986 <http://tools.ietf.org/html/rfc3986#section-5.2>`_ when merging base URLs and
  44. relative URLs.
  45. In the above example, we passed ``/user`` to the ``get()`` method of the client. This is a relative URL, so it will
  46. merge into the base URL of the client-- resulting in the derived URL of ``https://api.github.com/users``.
  47. ``/user`` is a relative URL but uses an absolute path because it contains the leading slash. Absolute paths will
  48. overwrite any existing path of the base URL. If an absolute path is provided (e.g. ``/path/to/something``), then the
  49. path specified in the base URL of the client will be replaced with the absolute path, and the query string provided
  50. by the relative URL will replace the query string of the base URL.
  51. Omitting the leading slash and using relative paths will add to the path of the base URL of the client. So using a
  52. client base URL of ``https://api.twitter.com/v1.1`` and creating a GET request with ``statuses/user_timeline.json``
  53. will result in a URL of ``https://api.twitter.com/v1.1/statuses/user_timeline.json``. If a relative path and a query
  54. string are provided, then the relative path will be appended to the base URL path, and the query string provided will
  55. be merged into the query string of the base URL.
  56. If an absolute URL is provided (e.g. ``http://httpbin.org/ip``), then the request will completely use the absolute URL
  57. as-is without merging in any of the URL parts specified in the base URL.
  58. Configuration options
  59. ~~~~~~~~~~~~~~~~~~~~~
  60. The second argument of the client's constructor is an array of configuration data. This can include URI template data
  61. or special options that alter the client's behavior:
  62. +-------------------------------+-------------------------------------------------------------------------------------+
  63. | ``request.options`` | Associative array of :ref:`Request options <request-options>` to apply to every |
  64. | | request created by the client. |
  65. +-------------------------------+-------------------------------------------------------------------------------------+
  66. | ``redirect.disable`` | Disable HTTP redirects for every request created by the client. |
  67. +-------------------------------+-------------------------------------------------------------------------------------+
  68. | ``curl.options`` | Associative array of cURL options to apply to every request created by the client. |
  69. | | if either the key or value of an entry in the array is a string, Guzzle will |
  70. | | attempt to find a matching defined cURL constant automatically (e.g. |
  71. | | "CURLOPT_PROXY" will be converted to the constant ``CURLOPT_PROXY``). |
  72. +-------------------------------+-------------------------------------------------------------------------------------+
  73. | ``ssl.certificate_authority`` | Set to true to use the Guzzle bundled SSL certificate bundle (this is used by |
  74. | | default, 'system' to use the bundle on your system, a string pointing to a file to |
  75. | | use a specific certificate file, a string pointing to a directory to use multiple |
  76. | | certificates, or ``false`` to disable SSL validation (not recommended). |
  77. | | |
  78. | | When using Guzzle inside of a phar file, the bundled SSL certificate will be |
  79. | | extracted to your system's temp folder, and each time a client is created an MD5 |
  80. | | check will be performed to ensure the integrity of the certificate. |
  81. +-------------------------------+-------------------------------------------------------------------------------------+
  82. | ``command.params`` | When using a ``Guzzle\Service\Client`` object, this is an associative array of |
  83. | | default options to set on each command created by the client. |
  84. +-------------------------------+-------------------------------------------------------------------------------------+
  85. Here's an example showing how to set various configuration options, including default headers to send with each request,
  86. default query string parameters to add to each request, a default auth scheme for each request, and a proxy to use for
  87. each request. Values can be injected into the client's base URL using variables from the configuration array.
  88. .. code-block:: php
  89. use Guzzle\Http\Client;
  90. $client = new Client('https://api.twitter.com/{version}', array(
  91. 'version' => 'v1.1',
  92. 'request.options' => array(
  93. 'headers' => array('Foo' => 'Bar'),
  94. 'query' => array('testing' => '123'),
  95. 'auth' => array('username', 'password', 'Basic|Digest|NTLM|Any'),
  96. 'proxy' => 'tcp://localhost:80'
  97. )
  98. ));
  99. Setting a custom User-Agent
  100. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  101. The default Guzzle User-Agent header is ``Guzzle/<Guzzle_Version> curl/<curl_version> PHP/<PHP_VERSION>``. You can
  102. customize the User-Agent header of a client by calling the ``setUserAgent()`` method of a Client object.
  103. .. code-block:: php
  104. // Completely override the default User-Agent
  105. $client->setUserAgent('Test/123');
  106. // Prepend a string to the default User-Agent
  107. $client->setUserAgent('Test/123', true);
  108. Creating requests with a client
  109. -------------------------------
  110. A Client object exposes several methods used to create Request objects:
  111. * Create a custom HTTP request: ``$client->createRequest($method, $uri, array $headers, $body, $options)``
  112. * Create a GET request: ``$client->get($uri, array $headers, $options)``
  113. * Create a HEAD request: ``$client->head($uri, array $headers, $options)``
  114. * Create a DELETE request: ``$client->delete($uri, array $headers, $body, $options)``
  115. * Create a POST request: ``$client->post($uri, array $headers, $postBody, $options)``
  116. * Create a PUT request: ``$client->put($uri, array $headers, $body, $options)``
  117. * Create a PATCH request: ``$client->patch($uri, array $headers, $body, $options)``
  118. .. code-block:: php
  119. use Guzzle\Http\Client;
  120. $client = new Client('http://baseurl.com/api/v1');
  121. // Create a GET request using Relative to base URL
  122. // URL of the request: http://baseurl.com/api/v1/path?query=123&value=abc)
  123. $request = $client->get('path?query=123&value=abc');
  124. $response = $request->send();
  125. // Create HEAD request using a relative URL with an absolute path
  126. // URL of the request: http://baseurl.com/path?query=123&value=abc
  127. $request = $client->head('/path?query=123&value=abc');
  128. $response = $request->send();
  129. // Create a DELETE request using an absolute URL
  130. $request = $client->delete('http://www.example.com/path?query=123&value=abc');
  131. $response = $request->send();
  132. // Create a PUT request using the contents of a PHP stream as the body
  133. // Specify custom HTTP headers
  134. $request = $client->put('http://www.example.com/upload', array(
  135. 'X-Header' => 'My Header'
  136. ), fopen('http://www.test.com/', 'r'));
  137. $response = $request->send();
  138. // Create a POST request and add the POST files manually
  139. $request = $client->post('http://localhost:8983/solr/update')
  140. ->addPostFiles(array('file' => '/path/to/documents.xml'));
  141. $response = $request->send();
  142. // Check if a resource supports the DELETE method
  143. $supportsDelete = $client->options('/path')->send()->isMethodAllowed('DELETE');
  144. $response = $request->send();
  145. Client objects create Request objects using a request factory (``Guzzle\Http\Message\RequestFactoryInterface``).
  146. You can inject a custom request factory into the Client using ``$client->setRequestFactory()``, but you can typically
  147. rely on a Client's default request factory.
  148. Static clients
  149. --------------
  150. You can use Guzzle's static client facade to more easily send simple HTTP requests.
  151. .. code-block:: php
  152. // Mount the client so that you can access it at \Guzzle
  153. Guzzle\Http\StaticClient::mount();
  154. $response = Guzzle::get('http://guzzlephp.org');
  155. Each request method of the static client (e.g. ``get()``, ``post()`, ``put()``, etc) accepts an associative array of request
  156. options to apply to the request.
  157. .. code-block:: php
  158. $response = Guzzle::post('http://test.com', array(
  159. 'headers' => array('X-Foo' => 'Bar'),
  160. 'body' => array('Test' => '123'),
  161. 'timeout' => 10
  162. ));
  163. .. _request-options:
  164. Request options
  165. ---------------
  166. Request options can be specified when creating a request or in the ``request.options`` parameter of a client. These
  167. options can control various aspects of a request including: headers to send, query string data, where the response
  168. should be downloaded, proxies, auth, etc.
  169. headers
  170. ~~~~~~~
  171. Associative array of headers to apply to the request. When specified in the ``$options`` argument of a client creational
  172. method (e.g. ``get()``, ``post()``, etc), the headers in the ``$options`` array will overwrite headers specified in the
  173. ``$headers`` array.
  174. .. code-block:: php
  175. $request = $client->get($url, array(), array(
  176. 'headers' => array('X-Foo' => 'Bar')
  177. ));
  178. Headers can be specified on a client to add default headers to every request sent by a client.
  179. .. code-block:: php
  180. $client = new Guzzle\Http\Client();
  181. // Set a single header using path syntax
  182. $client->setDefaultOption('headers/X-Foo', 'Bar');
  183. // Set all headers
  184. $client->setDefaultOption('headers', array('X-Foo' => 'Bar'));
  185. .. note::
  186. In addition to setting request options when creating requests or using the ``setDefaultOption()`` method, any
  187. default client request option can be set using a client's config object:
  188. .. code-block:: php
  189. $client->getConfig()->setPath('request.options/headers/X-Foo', 'Bar');
  190. query
  191. ~~~~~
  192. Associative array of query string parameters to the request. When specified in the ``$options`` argument of a client
  193. creational method, the query string parameters in the ``$options`` array will overwrite query string parameters
  194. specified in the `$url`.
  195. .. code-block:: php
  196. $request = $client->get($url, array(), array(
  197. 'query' => array('abc' => '123')
  198. ));
  199. Query string parameters can be specified on a client to add default query string parameters to every request sent by a
  200. client.
  201. .. code-block:: php
  202. $client = new Guzzle\Http\Client();
  203. // Set a single query string parameter using path syntax
  204. $client->setDefaultOption('query/abc', '123');
  205. // Set an array of default query string parameters
  206. $client->setDefaultOption('query', array('abc' => '123'));
  207. body
  208. ~~~~
  209. Sets the body of a request. The value supplied to the body option can be a ``Guzzle\Http\EntityBodyInterface``, string,
  210. fopen resource, or array when sending POST requests. When a ``body`` request option is supplied, the option value will
  211. overwrite the ``$body`` argument of a client creational method.
  212. auth
  213. ~~~~
  214. Specifies and array of HTTP authorization parameters parameters to use with the request. The array must contain the
  215. username in index [0], the password in index [1], and can optionally contain the authentication type in index [2].
  216. The available authentication types are: "Basic" (default), "Digest", "NTLM", or "Any".
  217. .. code-block:: php
  218. $request = $client->get($url, array(), array(
  219. 'auth' => array('username', 'password', 'Digest')
  220. ));
  221. // You can add auth headers to every request of a client
  222. $client->setDefaultOption('auth', array('username', 'password', 'Digest'));
  223. cookies
  224. ~~~~~~~
  225. Specifies an associative array of cookies to add to the request.
  226. allow_redirects
  227. ~~~~~~~~~~~~~~~
  228. Specifies whether or not the request should follow redirects. Requests will follow redirects by default. Set
  229. ``allow_redirects`` to ``false`` to disable redirects.
  230. save_to
  231. ~~~~~~~
  232. The ``save_to`` option specifies where the body of a response is downloaded. You can pass the path to a file, an fopen
  233. resource, or a ``Guzzle\Http\EntityBodyInterface`` object.
  234. See :ref:`Changing where a response is downloaded <request-set-response-body>` for more information on setting the
  235. `save_to` option.
  236. events
  237. ~~~~~~
  238. The `events` option makes it easy to attach listeners to the various events emitted by a request object. The `events`
  239. options must be an associative array mapping an event name to a Closure or array the contains a Closure and the
  240. priority of the event.
  241. .. code-block:: php
  242. $request = $client->get($url, array(), array(
  243. 'events' => array(
  244. 'request.before_send' => function (\Guzzle\Common\Event $e) {
  245. echo 'About to send ' . $e['request'];
  246. }
  247. )
  248. ));
  249. // Using the static client:
  250. Guzzle::get($url, array(
  251. 'events' => array(
  252. 'request.before_send' => function (\Guzzle\Common\Event $e) {
  253. echo 'About to send ' . $e['request'];
  254. }
  255. )
  256. ));
  257. plugins
  258. ~~~~~~~
  259. The `plugins` options makes it easy to attach an array of plugins to a request.
  260. .. code-block:: php
  261. // Using the static client:
  262. Guzzle::get($url, array(
  263. 'plugins' => array(
  264. new Guzzle\Plugin\Cache\CachePlugin(),
  265. new Guzzle\Plugin\Cookie\CookiePlugin()
  266. )
  267. ));
  268. exceptions
  269. ~~~~~~~~~~
  270. The `exceptions` option can be used to disable throwing exceptions for unsuccessful HTTP response codes
  271. (e.g. 404, 500, etc). Set `exceptions` to false to not throw exceptions.
  272. params
  273. ~~~~~~
  274. The `params` options can be used to specify an associative array of data parameters to add to a request. Note that
  275. these are not query string parameters.
  276. timeout / connect_timeout
  277. ~~~~~~~~~~~~~~~~~~~~~~~~~
  278. You can specify the maximum number of seconds to allow for an entire transfer to take place before timing out using
  279. the `timeout` request option. You can specify the maximum number of seconds to wait while trying to connect using the
  280. `connect_timeout` request option. Set either of these options to 0 to wait indefinitely.
  281. .. code-block:: php
  282. $request = $client->get('http://www.example.com', array(), array(
  283. 'timeout' => 20,
  284. 'connect_timeout' => 1.5
  285. ));
  286. verify
  287. ~~~~~~
  288. Set to true to enable SSL certificate validation (the default), false to disable SSL certificate validation, or supply
  289. the path to a CA bundle to enable verification using a custom certificate.
  290. cert
  291. ~~~~
  292. The `cert` option lets you specify a PEM formatted SSL client certificate to use with servers that require one. If the
  293. certificate requires a password, provide an array with the password as the second item.
  294. This would typically be used in conjunction with the `ssl_key` option.
  295. .. code-block:: php
  296. $request = $client->get('https://www.example.com', array(), array(
  297. 'cert' => '/etc/pki/client_certificate.pem'
  298. )
  299. $request = $client->get('https://www.example.com', array(), array(
  300. 'cert' => array('/etc/pki/client_certificate.pem', 's3cr3tp455w0rd')
  301. )
  302. ssl_key
  303. ~~~~~~~
  304. The `ssl_key` option lets you specify a file containing your PEM formatted private key, optionally protected by a password.
  305. Note: your password is sensitive, keep the PHP script containing it safe.
  306. This would typically be used in conjunction with the `cert` option.
  307. .. code-block:: php
  308. $request = $client->get('https://www.example.com', array(), array(
  309. 'ssl_key' => '/etc/pki/private_key.pem'
  310. )
  311. $request = $client->get('https://www.example.com', array(), array(
  312. 'ssl_key' => array('/etc/pki/private_key.pem', 's3cr3tp455w0rd')
  313. )
  314. proxy
  315. ~~~~~
  316. The `proxy` option is used to specify an HTTP proxy (e.g. `http://username:password@192.168.16.1:10`).
  317. debug
  318. ~~~~~
  319. The `debug` option is used to show verbose cURL output for a transfer.
  320. stream
  321. ~~~~~~
  322. When using a static client, you can set the `stream` option to true to return a `Guzzle\Stream\Stream` object that can
  323. be used to pull data from a stream as needed (rather than have cURL download the entire contents of a response to a
  324. stream all at once).
  325. .. code-block:: php
  326. $stream = Guzzle::get('http://guzzlephp.org', array('stream' => true));
  327. while (!$stream->feof()) {
  328. echo $stream->readLine();
  329. }
  330. Sending requests
  331. ----------------
  332. Requests can be sent by calling the ``send()`` method of a Request object, but you can also send requests using the
  333. ``send()`` method of a Client.
  334. .. code-block:: php
  335. $request = $client->get('http://www.amazon.com');
  336. $response = $client->send($request);
  337. Sending requests in parallel
  338. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  339. The Client's ``send()`` method accept a single ``Guzzle\Http\Message\RequestInterface`` object or an array of
  340. RequestInterface objects. When an array is specified, the requests will be sent in parallel.
  341. Sending many HTTP requests serially (one at a time) can cause an unnecessary delay in a script's execution. Each
  342. request must complete before a subsequent request can be sent. By sending requests in parallel, a pool of HTTP
  343. requests can complete at the speed of the slowest request in the pool, significantly reducing the amount of time
  344. needed to execute multiple HTTP requests. Guzzle provides a wrapper for the curl_multi functions in PHP.
  345. Here's an example of sending three requests in parallel using a client object:
  346. .. code-block:: php
  347. use Guzzle\Common\Exception\MultiTransferException;
  348. try {
  349. $responses = $client->send(array(
  350. $client->get('http://www.google.com/'),
  351. $client->head('http://www.google.com/'),
  352. $client->get('https://www.github.com/')
  353. ));
  354. } catch (MultiTransferException $e) {
  355. echo "The following exceptions were encountered:\n";
  356. foreach ($e as $exception) {
  357. echo $exception->getMessage() . "\n";
  358. }
  359. echo "The following requests failed:\n";
  360. foreach ($e->getFailedRequests() as $request) {
  361. echo $request . "\n\n";
  362. }
  363. echo "The following requests succeeded:\n";
  364. foreach ($e->getSuccessfulRequests() as $request) {
  365. echo $request . "\n\n";
  366. }
  367. }
  368. If the requests succeed, an array of ``Guzzle\Http\Message\Response`` objects are returned. A single request failure
  369. will not cause the entire pool of requests to fail. Any exceptions thrown while transferring a pool of requests will
  370. be aggregated into a ``Guzzle\Common\Exception\MultiTransferException`` exception.
  371. Plugins and events
  372. ------------------
  373. Guzzle provides easy to use request plugins that add behavior to requests based on signal slot event notifications
  374. powered by the
  375. `Symfony2 Event Dispatcher component <http://symfony.com/doc/2.0/components/event_dispatcher/introduction.html>`_. Any
  376. event listener or subscriber attached to a Client object will automatically be attached to each request created by the
  377. client.
  378. Using the same cookie session for each request
  379. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  380. Attach a ``Guzzle\Plugin\Cookie\CookiePlugin`` to a client which will in turn add support for cookies to every request
  381. created by a client, and each request will use the same cookie session:
  382. .. code-block:: php
  383. use Guzzle\Plugin\Cookie\CookiePlugin;
  384. use Guzzle\Plugin\Cookie\CookieJar\ArrayCookieJar;
  385. // Create a new cookie plugin
  386. $cookiePlugin = new CookiePlugin(new ArrayCookieJar());
  387. // Add the cookie plugin to the client
  388. $client->addSubscriber($cookiePlugin);
  389. .. _client-events:
  390. Events emitted from a client
  391. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  392. A ``Guzzle\Http\Client`` object emits the following events:
  393. +------------------------------+--------------------------------------------+------------------------------------------+
  394. | Event name | Description | Event data |
  395. +==============================+============================================+==========================================+
  396. | client.create_request | Called when a client creates a request | * client: The client |
  397. | | | * request: The created request |
  398. +------------------------------+--------------------------------------------+------------------------------------------+
  399. .. code-block:: php
  400. use Guzzle\Common\Event;
  401. use Guzzle\Http\Client;
  402. $client = new Client();
  403. // Add a listener that will echo out requests as they are created
  404. $client->getEventDispatcher()->addListener('client.create_request', function (Event $e) {
  405. echo 'Client object: ' . spl_object_hash($e['client']) . "\n";
  406. echo "Request object: {$e['request']}\n";
  407. });