PHP Guzzle HTTP Request Library Quickstart - Alternative to the WP HTTP API
Guzzle Almost the de facto HTTP standard library for the PHP language, WordPress has made the new version of the JSON API The plugin has deprecated the WP HTTP API in favor of using Guzzle for development, and there may come a day when the WP HTTP API will be completely enabled in favor of using Guzzle across the board, so if you haven't touched Guzzle before, here are some quick starts as well as the columns.
Send Request
We can use Guzzle's GuzzleHttpClientInterface object to send the request.
Create Client
use GuzzleHttpClient.
$client = new Client([
'base_uri' => 'http://httpbin.org', // the base URI for the relative request
'timeout' => 2.0, // You can set the default timeout for requests.
]);
Clients are immutable in Guzzle, which means that you can't change the default values used by the client after it has been created.The Client object can take an array of parameters:
base_uri Base URI
(string|UriInterface) The base URI is used to merge into a related URI, which can be a string or an instance of a UriInterface, and will be merged into the base URI when a related URL is supplied, following the rules described in RFC 3986, section 2.
// Create a client using the base URI
$client = new GuzzleHttpClient(['base_uri' => 'https://foo.com/api/']);
// Send a request to https://foo.com/api/test
$response = $client->request('GET', 'test');
// Send a request to https://foo.com/root
$response = $client->request('GET', '/root');
Don't want to read RFC 3986? here are some quick examples of base_uri vs. other URI processors:
| base_uri | URI | Result |
|---|---|---|
| http://foo.com | /bar | http://foo.com/bar |
| http://foo.com/foo | /bar | http://foo.com/bar |
| http://foo.com/foo | bar | http://foo.com/bar |
| http://foo.com/foo/ | bar | http://foo.com/foo/bar |
| http://foo.com | http://baz.com | http://baz.com |
| http://foo.com/?bar | bar | http://foo.com/bar |
handler
A (callback) function that transmits an HTTP request. This function is called with the Psr7HttpMessageRequestInterface and an array of arguments, and must return GuzzleHttpPromisePromiseInterface, which is satisfied by Psr7HttpMessageResponseInterface on success. The handler is a constructor method and cannot be overridden in the request parameters.
All other parameters passed in the (mixed) constructor are used as default parameters for each request.
Send Request
The methods of the Client object make it easy to send requests:
$response = $client->get('http://httpbin.org/get');
$response = $client->delete('http://httpbin.org/delete');
$response = $client->head('http://httpbin.org/get');
$response = $client->options('http://httpbin.org/get');
$response = $client->patch('http://httpbin.org/patch');
$response = $client->post('http://httpbin.org/post');
$response = $client->put('http://httpbin.org/put');
You can create a request and pass it to the Client when everything is ready:
use GuzzleHttpPsr7Request.
$request = new Request('PUT', 'http://httpbin.org/put');
$response = $client->send($request, ['timeout' => 2]);
The Client object provides a very flexible handler for transporting requests, including the request parameters, the middleware used for each request, and the base URI for transporting multiple related requests.
You can find more information on the Handlers and Middleware page to find out more about middleware.
asynchronous request
You can use the methods provided by the Client to create asynchronous requests:
$promise = $client->getAsync('http://httpbin.org/get');
$promise = $client->deleteAsync('http://httpbin.org/delete');
$promise = $client->headAsync('http://httpbin.org/get');
$promise = $client->optionsAsync('http://httpbin.org/get');
$promise = $client->patchAsync('http://httpbin.org/patch');
$promise = $client->postAsync('http://httpbin.org/post');
$promise = $client->putAsync('http://httpbin.org/put');
You can also use the Client's sendAsync() and requestAsync() methods:
use GuzzleHttpPsr7Request.
// Create the PSR-7 request object to be sent
$headers = ['X-Foo' => 'Bar']; $body = 'Hello!
$body = 'Hello!
$request = new Request('HEAD', 'http://httpbin.org/head', $headers, $body);
// Or, if you don't need to pass in a request instance:
$promise = $client->requestAsync('GET', 'http://httpbin.org/get');
These methods return a Promise object that implements the Promises/A+ spec provided by the Guzzle promises library, which means that you can use then() to call the return value, succeeding with the PsrHttpMessageResponseInterface handler and throwing an exception otherwise. an exception is thrown otherwise.
use PsrHttpMessageResponseInterface;
use GuzzleHttpExceptionRequestException.
$promise = $client->requestAsync('GET', 'http://httpbin.org/get');
$promise->then(
function (ResponseInterface $res) {
echo $res->getStatusCode() . "n";
},
function (RequestException $e) {
echo $e->getMessage() . "n"; echo $e->getMessage() .
echo $e->getRequest()->getMethod();
}
).;
Concurrent requests
You can use Promise and asynchronous requests to send multiple requests at the same time:
use GuzzleHttpClient; use GuzzleHttpPromise; use GuzzleHttpPromise
use GuzzleHttpPromise.
$client = new Client(['base_uri' => 'http://httpbin.org/']);
// Start each request, but don't block
$promises = [
'image' => $client->getAsync('/image'),
'png' => $client->getAsync('/image/png'),
'jpeg' => $client->getAsync('/image/jpeg'),
'webp' => $client->getAsync('/image/webp')
]
// Wait for all requests to complete
$results = Promiseunwrap($promises);
// You can access each result using the key provided to the unwrap function.
echo $results['image']->getHeader('Content-Length');
echo $results['png']->getHeader('Content-Length'); echo $results['image']->getHeader('Content-Length');
You can use the GuzzleHttpPool object when you want to send an indeterminate number of requests:
use GuzzleHttpPool;
use GuzzleHttpClient; use GuzzleHttpPsr7Request
use GuzzleHttpPsr7Request; use GuzzleHttpPsr7Request.
$client = new Client(); use GuzzleHttpClient; use GuzzleHttpPsr7Request
$requests = function ($total) {
$uri = 'http://127.0.0.1:8126/guzzle-server/perf';
for ($i = 0; $i 5,
'fulfilled' => function ($response, $index) {
// Execute on each successful request
}, 'fulfilled' => function ($response, $index)
'rejected' => function ($reason, $index) {
// Executed on every failed request
}, 'rejected' => function
]);
// Start the transfer and create a promise
$promise = $pool->promise();
// Wait for the request pool to complete
$promise->wait();
Using Responses
In the previous example, we fetched the $response variable, or got the response from the Promise. The Response object implements a PSR-7 interface, PsrHttpMessageResponseInterface, which contains a lot of useful information.
You can get the status code and reason phrase of this response:
$code = $response->getStatusCode(); // 200
$reason = $response->getReasonPhrase(); // OK
You can get the header information from the response:
// Check if the header exists
if ($response->hasHeader('Content-Length')) {
echo "It exists"; }
}
// Get the request from the response
echo $response->getHeader('Content-Length'); } // Get the request from the response.
// Get all the response headers
foreach ($response->getHeaders() as $name => $values) {
echo $name . ': ' . implode(', ', $values) . "rn";
}
Use the getBody method to get the Body of the response, which can be used as a string or a stream object:
$body = $response->getBody();
// Display the body directly as a string
echo $body;
// assign body as a string to a variable
$stringBody = (string) $body; // assign body to a variable as a string.
// Read the first 10 bytes of the body content.
$tenBytes = $body->read(10);
// Read the rest of the body content as a string Read
$remainingBytes = $body->getContents(); // Read the rest of the body content as a string.;
Query String Parameters
There are a number of ways you can provide the query string for a request, and you can set the query string in the URI of the request:
$response = $client->request('GET', 'http://httpbin.org?foo=bar');
You can declare query string parameters using the query request parameter:
$client->request('GET', 'http://httpbin.org', [
'query' => ['foo' => 'bar']
]);
The supplied array parameter will use PHP's http_build_query:
Finally, you can provide a string as a query request parameter:
$client->request('GET', 'http://httpbin.org', ['query' => 'foo=bar']);
Upload data
Guzzle provides a number of methods for uploading data. You can send a request containing a stream of data, set the body request parameter to a string, the resource returned by fopen, or an instance of PsrHttpMessageStreamInterface.
// Provide the body content as a string
$r = $client->request('POST', 'http://httpbin.org/post', [
'body' => 'raw data'
]);
// Provide an fopen resource
$body = fopen('/path/to/file', 'r');
$r = $client->request('POST', 'http://httpbin.org/post', ['body' => $body]);
// Create a PSR-7 stream using the stream_for() function.
$body = GuzzleHttpPsr7stream_for('hello!');
$r = $client->request('POST', 'http://httpbin.org/post', ['body' => $body]);
Uploading JSON data and setting the appropriate headers can be done in a simple way using the json request parameter:
$r = $client->request('PUT', 'http://httpbin.org/put', [
'json' => ['foo' => 'bar']
]);
POST/Form Request
In addition to using the body parameter to specify the request data, Guzzle provides a useful way to send POST data.
Send form fields
dispatch application/x-www-form-urlencoded POST requests require you to pass in form_params An array of parameters specifying the fields of the POST within the array.
$response = $client->request('POST', 'http://httpbin.org/post', [
'form_params' => [
'nested_field' => [
'nested' => 'hello'
]
]
]);
Send Form Files
You can send a form (the form enctype attribute needs to be set to multipart/form-data ) file by using the multipart request parameter, which receives an array containing multiple associative arrays, each containing the name of a key:
- name: (required, string) The name to map to the form field.
- contents: (mandatory, mixed) Provide a string that can be either the resource returned by fopen, or a
Instance of PsrHttpMessageStreamInterface.
response = $client->request('POST', 'http://httpbin.org/post', [
'multipart' => [
[
'contents' => 'abc'
], [
[
'name' => 'file_name', 'contents' => fopen('/path/to/file', 'r')
'contents' => fopen('/path/to/file', 'r')
], [
[
'headers' => [
'X-Foo' => 'this is an extra header to include'
]
]
]
]).;
Cookies
Guzzle can maintain a cookie session for you using the Cookies request parameter. When sending a request, the Cookies option must be set to an instance of GuzzleHttpCookieCookieJarInterface.
// Use a specified cookie
$jar = new GuzzleHttpCookieCookieJar;
$r = $client->request('GET', 'http://httpbin.org/cookies', [
'cookies' => $jar
]);
If you want to share cookies across all requests, you can set Cookies to true in the client constructor.
// Client that uses a common cookie
$client = new GuzzleHttpClient(['cookie' => true]);
$r = $client->request('GET', 'http://httpbin.org/cookies');
redirects
If you don't tell Guzzle not to redirect, Guzzle will do it automatically, and you can customize the redirection behavior using the allow_redirects request parameter.
- Setting it to true enables a maximum number of redirects of 5, which is the default setting.
- Set to false to disable redirection.
- Pass an associative array of max keywords to declare the maximum number of redirects, and an optional strict keyword to declare whether to use strict RFC standard redirects (indicating that POST requests are redirected using POST vs. most browsers use GET requests to redirect POST requests).
$response = $client->request('GET', 'http://github.com');
echo $response->getStatusCode(); // 200
The following columns indicate that redirection is disabled:
$response = $client->request('GET', 'http://github.com', [
'allow_redirects' => false
]);
echo $response->getStatusCode();
exceptions
Guzzle will throw an exception if an error occurs during the transmission of the request.
- The GuzzleHttpExceptionRequestException is thrown when a network error (connection timeout, DNS error, etc.) is sent. This exception is inherited from GuzzleHttpExceptionTransferException and catching this exception will throw an exception during the transfer request.
use GuzzleHttpExceptionRequestException.;
try {
$client->request('GET', 'https://github.com/_abc_123_404');
} catch (RequestException $e) {
echo $e->getRequest();
if ($e->hasResponse()) {
echo $e->getResponse();
}
} - GuzzleHttpExceptionConnectException The GuzzleHttpExceptionConnectException occurs on a network error and is inherited from GuzzleHttpExceptionRequestException.
- If the http_errors request parameter is set to true, a GuzzleHttpExceptionClientException is thrown on a 400 level error, which inherits from GuzzleHttpExceptionBadResponseException. GuzzleHttpExceptionBadResponseException inherits from GuzzleHttpExceptionRequestException.
use GuzzleHttpExceptionClientException.;
try {
$client->request('GET', 'https://github.com/_abc_123_404');
} catch (ClientException $e) {
echo $e->getRequest();
echo $e->getResponse();
} - If the http_errors request parameter is set to true, the GuzzleHttpExceptionServerException is thrown on a 500 level error. This exception inherits from GuzzleHttpExceptionBadResponseException.
- GuzzleHttpExceptionTooManyRedirectsException occurs when there are too many redirects and is inherited from GuzzleHttpExceptionRequestException.
All of the above exceptions inherit from GuzzleHttpExceptionTransferException.
environment variable
Guzzle provides some customizable environment variables:
GUZZLE_CURL_SELECT_TIMEOUT
When using curl_multi_select() in the Curl processor to control the duration that curl_multi_* needs to be used for, some systems have problems with implementing PHP's curl_multi_select(), which is always called waiting for the maximum timeout value.
HTTP_PROXY
Defines the proxy to be used when sending requests using the Http protocol.
HTTPS_PROXY
Defines the proxy to be used when sending requests using the Https protocol.