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 requestGuzzleHttp\Client::post
: Sends a POST requestGuzzleHttp\Client::put
: Sends a PUT requestGuzzleHttp\Client::delete
: Sends a DELETE requestGuzzleHttp\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.
$client = new GuzzleHttp\Client();
$client->put('http://httpbin.org', [
'headers' => ['X-Foo' => 'Bar'],
'body' => 'this is the body!',
'save_to' => '/path/to/local/file',
'allow_redirects' => false,
'timeout' => 5
]);
Synchronous Error Handling
When a recoverable error is encountered while calling the send()
method of a client, a GuzzleHttp\Exception\RequestException
is thrown.
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
$client = new Client();
try {
$client->get('http://httpbin.org');
} catch (RequestException $e) {
echo $e->getRequest() . "\n";
if ($e->hasResponse()) {
echo $e->getResponse() . "\n";
}
}
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.
$response = $client->put('http://httpbin.org/get', ['future' => true]);
// Call the function when the response completes
$response->then(function ($response) {
echo $response->getStatusCode();
});
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.
$response = $client->put('http://httpbin.org/get', ['future' => true]);
// Block until the response has completed
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.
$response = $client->put('http://httpbin.org/get', ['future' => true]);
$response
->then(
function ($response) {
// This is called when the request succeeded
echo 'Success: ' . $response->getStatusCode();
// Returning a value will forward the value to the next promise
// in the chain.
return $response;
},
function ($error) {
// This is called when the exception failed.
echo 'Exception: ' . $error->getMessage();
// Throwing will "forward" the exception to the next promise
// in the chain.
throw $error;
}
)
->then(
function($response) {
// This is called after the first promise in the chain. It
// receives the value returned from the first promise.
echo $response->getReasonPhrase();
},
function ($error) {
// This is called if the first promise error handler in the
// chain rethrows the exception.
echo 'Error: ' . $error->getMessage();
}
);
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.
$request = $client->createRequest('GET', 'http://httpbin.org', [
'headers' => ['X-Foo' => 'Bar']
]);
// Modify the request as needed
$request->setHeader('Baz', 'bar');
After creating a request, you can send it with the client’s send()
method.
$response = $client->send($request);