Sending Requests

Requests can be created using various methods of a client. You can create and send requests using one of the following methods:

  • GuzzleHttp\Client::get: Sends a GET request.
  • GuzzleHttp\Client::head: Sends a HEAD request
  • GuzzleHttp\Client::post: Sends a POST request
  • GuzzleHttp\Client::put: Sends a PUT request
  • GuzzleHttp\Client::delete: Sends a DELETE request
  • GuzzleHttp\Client::options: Sends an OPTIONS request

Each of the above methods accepts a URL as the first argument and an optional associative array of Request Options as the second argument.

Synchronous Requests

Guzzle sends synchronous (blocking) requests when the future request option is not specified. This means that the request will complete immediately, and if an error is encountered, a GuzzleHttp\Exception\RequestException will be thrown.

  1. $client = new GuzzleHttp\Client();
  2. $client->put('http://httpbin.org', [
  3. 'headers' => ['X-Foo' => 'Bar'],
  4. 'body' => 'this is the body!',
  5. 'save_to' => '/path/to/local/file',
  6. 'allow_redirects' => false,
  7. 'timeout' => 5
  8. ]);

Synchronous Error Handling

When a recoverable error is encountered while calling the send() method of a client, a GuzzleHttp\Exception\RequestException is thrown.

  1. use GuzzleHttp\Client;
  2. use GuzzleHttp\Exception\RequestException;
  3. $client = new Client();
  4. try {
  5. $client->get('http://httpbin.org');
  6. } catch (RequestException $e) {
  7. echo $e->getRequest() . "\n";
  8. if ($e->hasResponse()) {
  9. echo $e->getResponse() . "\n";
  10. }
  11. }

GuzzleHttp\Exception\RequestException always contains a GuzzleHttp\Message\RequestInterface object that can be accessed using the exception’s getRequest() method.

A response might be present in the exception. In the event of a networking error, no response will be received. You can check if a RequestException has a response using the hasResponse() method. If the exception has a response, then you can access the associated GuzzleHttp\Message\ResponseInterface using the getResponse() method of the exception.

Asynchronous Requests

You can send asynchronous requests by setting the future request option to true (or a string that your handler understands). This creates a GuzzleHttp\Message\FutureResponse object that has not yet completed. Once you have a future response, you can use a promise object obtained by calling the then method of the response to take an action when the response has completed or encounters an error.

  1. $response = $client->put('http://httpbin.org/get', ['future' => true]);
  2. // Call the function when the response completes
  3. $response->then(function ($response) {
  4. echo $response->getStatusCode();
  5. });

You can call the wait() method of a future response to block until it has completed. You also use a future response object just like a normal response object by accessing the methods of the response. Using a future response like a normal response object, also known as dereferencing, will block until the response has completed.

  1. $response = $client->put('http://httpbin.org/get', ['future' => true]);
  2. // Block until the response has completed
  3. echo $response->getStatusCode();

Important

If an exception occurred while transferring the future response, then the exception encountered will be thrown when dereferencing.

Note

It depends on the RingPHP handler used by a client, but you typically need to use the same RingPHP handler in order to utilize asynchronous requests across multiple clients.

Asynchronous Error Handling

Handling errors with future response object promises is a bit different. When using a promise, exceptions are forwarded to the $onError function provided to the second argument of the then() function.

  1. $response = $client->put('http://httpbin.org/get', ['future' => true]);
  2. $response
  3. ->then(
  4. function ($response) {
  5. // This is called when the request succeeded
  6. echo 'Success: ' . $response->getStatusCode();
  7. // Returning a value will forward the value to the next promise
  8. // in the chain.
  9. return $response;
  10. },
  11. function ($error) {
  12. // This is called when the exception failed.
  13. echo 'Exception: ' . $error->getMessage();
  14. // Throwing will "forward" the exception to the next promise
  15. // in the chain.
  16. throw $error;
  17. }
  18. )
  19. ->then(
  20. function($response) {
  21. // This is called after the first promise in the chain. It
  22. // receives the value returned from the first promise.
  23. echo $response->getReasonPhrase();
  24. },
  25. function ($error) {
  26. // This is called if the first promise error handler in the
  27. // chain rethrows the exception.
  28. echo 'Error: ' . $error->getMessage();
  29. }
  30. );

Please see the React/Promises project documentation for more information on how promise resolution and rejection forwarding works.

HTTP Errors

If the exceptions request option is not set to false, then exceptions are thrown for HTTP protocol errors as well: GuzzleHttp\Exception\ClientErrorResponseException for 4xx level HTTP responses and GuzzleHttp\Exception\ServerException for 5xx level responses, both of which extend from GuzzleHttp\Exception\BadResponseException.

Creating Requests

You can create a request without sending it. This is useful for building up requests over time or sending requests in concurrently.

  1. $request = $client->createRequest('GET', 'http://httpbin.org', [
  2. 'headers' => ['X-Foo' => 'Bar']
  3. ]);
  4. // Modify the request as needed
  5. $request->setHeader('Baz', 'bar');

After creating a request, you can send it with the client’s send() method.

  1. $response = $client->send($request);