Making a Request

You can send requests with Guzzle using a GuzzleHttp\ClientInterface object.

Creating a Client

  1. use GuzzleHttp\Client;
  2. $client = new Client([
  3. // Base URI is used with relative requests
  4. 'base_uri' => 'http://httpbin.org',
  5. // You can set any number of default request options.
  6. 'timeout' => 2.0,
  7. ]);

Clients are immutable in Guzzle 6, which means that you cannot change the defaults used by a client after it’s created.

The client constructor accepts an associative array of options:

base_uri

(string|UriInterface) Base URI of the client that is merged into relative URIs. Can be a string or instance of UriInterface. When a relative URI is provided to a client, the client will combine the base URI with the relative URI using the rules described in RFC 3986, section 5.2.

  1. // Create a client with a base URI
  2. $client = new GuzzleHttp\Client(['base_uri' => 'https://foo.com/api/']);
  3. // Send a request to https://foo.com/api/test
  4. $response = $client->request('GET', 'test');
  5. // Send a request to https://foo.com/root
  6. $response = $client->request('GET', '/root');

Don’t feel like reading RFC 3986? Here are some quick examples on how a base_uri is resolved with another URI.

base_uriURIResult
http://foo.com/barhttp://foo.com/bar
http://foo.com/foo/barhttp://foo.com/bar
http://foo.com/foobarhttp://foo.com/bar
http://foo.com/foo/barhttp://foo.com/foo/bar
http://foo.comhttp://baz.comhttp://baz.com
http://foo.com/?barbarhttp://foo.com/bar

handler

(callable) Function that transfers HTTP requests over the wire. The function is called with a Psr7\Http\Message\RequestInterface and array of transfer options, and must return a GuzzleHttp\Promise\PromiseInterface that is fulfilled with a Psr7\Http\Message\ResponseInterface on success.

...

(mixed) All other options passed to the constructor are used as default request options with every request created by the client.

Sending Requests

Magic methods on the client make it easy to send synchronous requests:

  1. $response = $client->get('http://httpbin.org/get');
  2. $response = $client->delete('http://httpbin.org/delete');
  3. $response = $client->head('http://httpbin.org/get');
  4. $response = $client->options('http://httpbin.org/get');
  5. $response = $client->patch('http://httpbin.org/patch');
  6. $response = $client->post('http://httpbin.org/post');
  7. $response = $client->put('http://httpbin.org/put');

You can create a request and then send the request with the client when you’re ready:

  1. use GuzzleHttp\Psr7\Request;
  2. $request = new Request('PUT', 'http://httpbin.org/put');
  3. $response = $client->send($request, ['timeout' => 2]);

Client objects provide a great deal of flexibility in how request are transferred including default request options, default handler stack middleware that are used by each request, and a base URI that allows you to send requests with relative URIs.

You can find out more about client middleware in the Handlers and Middleware page of the documentation.

Async Requests

You can send asynchronous requests using the magic methods provided by a client:

  1. $promise = $client->getAsync('http://httpbin.org/get');
  2. $promise = $client->deleteAsync('http://httpbin.org/delete');
  3. $promise = $client->headAsync('http://httpbin.org/get');
  4. $promise = $client->optionsAsync('http://httpbin.org/get');
  5. $promise = $client->patchAsync('http://httpbin.org/patch');
  6. $promise = $client->postAsync('http://httpbin.org/post');
  7. $promise = $client->putAsync('http://httpbin.org/put');

You can also use the sendAsync() and requestAsync() methods of a client:

  1. use GuzzleHttp\Psr7\Request;
  2. // Create a PSR-7 request object to send
  3. $headers = ['X-Foo' => 'Bar'];
  4. $body = 'Hello!';
  5. $request = new Request('HEAD', 'http://httpbin.org/head', $headers, $body);
  6. $promise = $client->sendAsync($request);
  7. // Or, if you don't need to pass in a request instance:
  8. $promise = $client->requestAsync('GET', 'http://httpbin.org/get');

The promise returned by these methods implements the Promises/A+ spec, provided by the Guzzle promises library. This means that you can chain then() calls off of the promise. These then calls are either fulfilled with a successful Psr\Http\Message\ResponseInterface or rejected with an exception.

  1. use Psr\Http\Message\ResponseInterface;
  2. use GuzzleHttp\Exception\RequestException;
  3. $promise = $client->requestAsync('GET', 'http://httpbin.org/get');
  4. $promise->then(
  5. function (ResponseInterface $res) {
  6. echo $res->getStatusCode() . "\n";
  7. },
  8. function (RequestException $e) {
  9. echo $e->getMessage() . "\n";
  10. echo $e->getRequest()->getMethod();
  11. }
  12. );

Concurrent requests

You can send multiple requests concurrently using promises and asynchronous requests.

  1. use GuzzleHttp\Client;
  2. use GuzzleHttp\Promise;
  3. $client = new Client(['base_uri' => 'http://httpbin.org/']);
  4. // Initiate each request but do not block
  5. $promises = [
  6. 'image' => $client->getAsync('/image'),
  7. 'png' => $client->getAsync('/image/png'),
  8. 'jpeg' => $client->getAsync('/image/jpeg'),
  9. 'webp' => $client->getAsync('/image/webp')
  10. ];
  11. // Wait for the requests to complete; throws a ConnectException
  12. // if any of the requests fail
  13. $responses = Promise\unwrap($promises);
  14. // You can access each response using the key of the promise
  15. echo $responses['image']->getHeader('Content-Length')[0];
  16. echo $responses['png']->getHeader('Content-Length')[0];
  17. // Wait for the requests to complete, even if some of them fail
  18. $responses = Promise\settle($promises)->wait();
  19. // Values returned above are wrapped in an array with 2 keys: "state" (either fulfilled or rejected) and "value" (contains the response)
  20. echo $responses['image']['state']; // returns "fulfilled"
  21. echo $responses['image']['value']->getHeader('Content-Length')[0];
  22. echo $responses['png']['value']->getHeader('Content-Length')[0];

You can use the GuzzleHttp\Pool object when you have an indeterminate amount of requests you wish to send.

  1. use GuzzleHttp\Client;
  2. use GuzzleHttp\Exception\RequestException;
  3. use GuzzleHttp\Pool;
  4. use GuzzleHttp\Psr7\Request;
  5. use GuzzleHttp\Psr7\Response;
  6. $client = new Client();
  7. $requests = function ($total) {
  8. $uri = 'http://127.0.0.1:8126/guzzle-server/perf';
  9. for ($i = 0; $i < $total; $i++) {
  10. yield new Request('GET', $uri);
  11. }
  12. };
  13. $pool = new Pool($client, $requests(100), [
  14. 'concurrency' => 5,
  15. 'fulfilled' => function (Response $response, $index) {
  16. // this is delivered each successful response
  17. },
  18. 'rejected' => function (RequestException $reason, $index) {
  19. // this is delivered each failed request
  20. },
  21. ]);
  22. // Initiate the transfers and create a promise
  23. $promise = $pool->promise();
  24. // Force the pool of requests to complete.
  25. $promise->wait();

Or using a closure that will return a promise once the pool calls the closure.

  1. $client = new Client();
  2. $requests = function ($total) use ($client) {
  3. $uri = 'http://127.0.0.1:8126/guzzle-server/perf';
  4. for ($i = 0; $i < $total; $i++) {
  5. yield function() use ($client, $uri) {
  6. return $client->getAsync($uri);
  7. };
  8. }
  9. };
  10. $pool = new Pool($client, $requests(100));