sf43 Httpclient Cheat Sheet
sf43 Httpclient Cheat Sheet
org
Consume APIs in a snap! Provides utilities to
HttpClient is a
Install standalone package
$statusCode = $response->getStatusCode();
returns the status code
getting the response headers E.g.: 200
waits until they arrive
$contentType = $response->getHeaders()['content-type'][0];
returns: ‘application/json’
Only supported
when using cURL
HTTP/2 will be used by default if:
* cURL-based transport used
HTTPClient supports
HTTP/2 request * libcurl version is >= 7.36 native PHP streams
* request using HTTPs protocol
and cURL
To enable for HTTP requests:
HttpClient::create() selects cURL transport if cURL PHP
$httpClient = HttpClient::create(['http_version' => '2.0']); extension is enabled and falls back to PHP streams otherwise.
HttpClient
4.3 Options for Create and Request
option default value definition and examples
authentication
auth_basic null An array containing the username as first value, and optionally the password as the second one; or string
like username:password - enabling HTTP Basic authentication (RFC 7617).
Use the same authentication
auth_bearer null A token enabling HTTP Bearer authorization (RFC 6750). for all requests
$httpClient = HttpClient::create([ HTTP Basic authentication
'auth_basic' => ['the-username'], with only the username
'auth_basic' => ['the-username', 'the-password'], HTTP Basic authentication
with username and password
'auth_bearer' => 'the-bearer-token', HTTP Bearer authentication
]); (also called token authentication)
body ‘' You can use regular strings, closures, iterables and resources to upload data.
They'll be processed automatically when making the requests.
$response = $httpClient->request('POST', 'https://...', [
'body' => 'raw data', using a regular string
using an array
'body' => ['parameter1' => 'value1', '...'],
of parameters
'body' => function () {
// ... using a closure to generate
}, the uploaded data
'body' => fopen('/path/to/file', 'r'), using a resource to
]); get the data from it
json null
json payload
When uploading JSON payloads, use the json option instead of body. The given content will be JSON-encoded
automatically and the request will add the Content-Type: application/json automatically too.
$response = $httpClient->request('POST', 'https://...', [
'json' => ['param1' => 'value1', '...'],
]);
user_data null Any extra data to attach to the request (scalar, callable, object...) that
must be available via $response->getInfo('user_data') - not used internally.
max_redirects 20 The maximum number of redirects to follow; a value lower or equal to zero means redirects should not be followed;
"Authorization" and "Cookie" headers must not follow except for the initial host name.
If the number of redirects is higher than the configured value, you'll get a RedirectionException.
http_version null Defaults to the best supported version, typically 1.1 or 2.0.
base_uri null The URI to resolve relative URLs, following rules in RFC 3986, section 2 .
buffer true Whether the content of the response should be buffered or not.
By https://andreiabohner.org
PSR-18 compatible
HttpClient
4.3
option default value definition and examples
on_progress null Details about the response progress (e.g. display a progress bar) / abort a request throwing any exceptions.
$url = 'https://releases.ubuntu.com/18.04.1/ubuntu-18.04.1-desktop-amd64.iso';
$response = $httpClient->request('GET', $url, [
'on_progress' => function (int $dlNow, int $dlSize, array $info): void {
// ...
}, optional: to display details
]); about the response progress
proxy null Get through an HTTP proxy. By default, the proxy-related env vars handled by cURL should be honored.
no_proxy null A comma separated list of hosts that do not require a proxy to be reached.
verify_peer true
SSL / certificates (https://php.net/context.ssl)
verify_host true
cafile null Location of Certificate Authority file on local filesystem which should be used with the verify_peer context option
to authenticate the identity of the remote peer.
capath null If cafile is not specified or if the certificate is not found there, the directory pointed to by capath is searched for a
suitable certificate. capath must be a correctly hashed certificate directory.
local_pk null Path to local private key file on filesystem in case of separate files for certificate (local_cert) and private key.
passphrase null Passphrase with which your local_cert file was encoded.
peer_fingerprint null Pin public keys of remote certificates. Aborts when the remote certificate digest doesn't match the specified hash.
capture_peer_cert_chain false If set to TRUE a peer_certificate_chain context option will be created containing the certificate chain.
extra [] Additional options that can be ignored if unsupported, unlike regular options
use Symfony\Component\HttpClient\HttpClient;
use Symfony\Component\HttpClient\CachingHttpClient;
use Symfony\Component\HttpKernel\HttpCache\Store;
accepts a third argument
$store = new Store('/path/to/cache/storage/'); to set the options for
$client = HttpClient::create(); HttpCache
$client = new CachingHttpClient($client, $store); won't hit the network
if the resource is already
$response = $client->request('GET', 'https://example.com/cacheable-resource'); in the cache
By https://andreiabohner.org
Supports synchronous and
redirect_count
start_time
use Symfony\Component\HttpClient\HttpClient;
use Symfony\Component\HttpClient\ScopingHttpClient;
$client = HttpClient::create();
the key is a regexp
$httpClient = new ScopingHttpClient($client, [
which must match the options defined as values
'https://api\.github\.com/' => [
the beginning of 'headers' => [ apply only to the URLs
the request URL 'Accept' => 'application/vnd.github.v3+json', matching the regular
'Authorization' => 'token '.$githubToken, expressions defined as key
],
the (optional) 3rd 'base_uri' => 'https://api.github.com/',
argument is the ],
regexp applied to ],
all relative URLs 'https://api\.github\.com/'
(when using base_uri) );
By https://andreiabohner.org
HttpClient
you can configure multiple clients with
different configurations and inject
them into your services
4.3
Symfony Framework Integration
# config/packages/framework.yaml # config/packages/framework.yaml
framework: framework:
# ... Use the http_client # ... Defining multiple
http_client: key to configure the http_client: http_clients
max_host_connections: 10 default HTTP client scoped_clients:
default_options: crawler.client:
max_redirects: 7
used in the app headers: { 'X-Powered-By': 'ACME App' }
http_version: '1.0'
some_api.client:
max_redirects: 5
Handling Exceptions
When the HTTP status code of the response is in the 300-599 range (i.e. 3xx, 4xx or 5xx) your code is expected to handle it.
If you don't do that, the getHeaders() and getContent() methods throw an appropriate exception:
the response of this
$response = $httpClient->request('GET', 'https://httpbin.org/status/403'); request will be a
403 HTTP error
// this code results in a Symfony\Component\HttpClient\Exception\ClientException
// because it doesn't check the status code of the response
$content = $response->getContent();
pass FALSE as the optional argument to
not throw an exception and return
$content = $response->getContent(false); instead the original response content
(even if it's an error message)