In addition to the new HTTP recorder and the support for HTTP trailers, Symfony 8.2 improves the HttpClient component with more features.

Cache Policies for Cached Responses

Nicolas Grekas Pascal CESCON
Contributed by Nicolas Grekas and Pascal CESCON in #65123

Symfony 7.4 revamped the caching HTTP client to make it fully compliant with RFC 9111. However, it stored responses based only on their cache headers, and there was no way to tag a cached response to invalidate it later.

Symfony 8.2 adds the extra.cache_policy option to CachingHttpClient. It's a callable that receives a CachePolicy object, the status code and the headers of the response, and decides how the response is stored:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
use Symfony\Component\HttpClient\CachePolicy;

$response = $client->request('GET', 'https://api.example.com/products/42', [
    'extra' => [
        'cache_policy' => function (CachePolicy $cache, int $statusCode, array $headers): void {
            // tag the stored response to invalidate it later
            $cache->tag('product-42');

            // store it for one hour, whatever its cache headers say
            $cache->expiresAfter(3600);
        },
    ],
]);

// later, when the product changes, remove its cached responses using
// the tag-aware cache pool used by the caching client
$cachePool->invalidateTags(['product-42']);

If the tags depend on the contents of the response, use tagFromBody(). It requires the buffer option to be true (otherwise, the tags are ignored and a warning is logged):

1
2
3
4
5
'cache_policy' => function (CachePolicy $cache): void {
    $cache->tagFromBody(
        fn (string $body): array => ['product-'.json_decode($body, true)['id']]
    );
},

Caching QUERY Requests

Ayyoub AFW-ALLAH
Contributed by Ayyoub AFW-ALLAH in #64874

The HTTP QUERY method is a safe and idempotent method, like GET, that sends the query in the request body instead of the URL. Until now, CachingHttpClient only cached GET and HEAD requests, and any request with a body bypassed the cache.

In Symfony 8.2, QUERY requests are cacheable too:

1
2
3
4
$response = $client->request('QUERY', 'https://api.example.com/products', [
    'headers' => ['Content-Type' => 'application/json'],
    'body' => json_encode(['category' => 'books', 'maxPrice' => 20]),
]);

The request body and its Content-Type are part of the cache key, so each different query is cached separately. The cache is bypassed when the request doesn't define a Content-Type header or when its body is not a string (e.g. a stream or a closure).

Repeated Fields in Query Strings and Bodies

Grégoire Pineau
Contributed by Grégoire Pineau in #66376

Many HTTP APIs expect multi-valued parameters as repeated keys (?name=web&name=api). That's the default serialization of arrays in OpenAPI 3 and what most HTTP libraries in other languages generate. However, the query and body options always generated the PHP-style syntax (?name[0]=web&name[1]=api), so you had to build those URLs by hand.

In Symfony 8.2, both options also accept a list of single-entry arrays, where field names can be repeated:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$client->request('GET', 'https://consul.example.com/v1/connect/intentions/match', [
    'query' => [['by' => 'destination'], ['name' => 'web'], ['name' => 'api']],
]);
// GET /v1/connect/intentions/match?by=destination&name=web&name=api

// in bodies, values can also be streams, e.g. to upload several files
// using the same field name
$client->request('POST', 'https://api.example.com/documents', [
    'body' => [
        ['tag' => 'invoice'],
        ['tag' => '2026'],
        ['file' => fopen('/path/to/invoice.pdf', 'r')],
        ['file' => fopen('/path/to/receipt.pdf', 'r')],
    ],
]);

Associative arrays keep working as before. Values in these lists must be scalars, \Stringable objects, backed enums or null (which removes the parameter); nested arrays throw an exception, so write the brackets yourself if you need them (['tag[]' => 'invoice']).

Caution

This changes the meaning of lists whose first item is an array. For example, [['a' => 'b']] was previously encoded as 0[a]=b and now it generates a=b.

Retrying Requests Against Other Base URIs

Benjamin Zaslavsky
Contributed by Benjamin Zaslavsky in #53131

Since Symfony 6.3, RetryableHttpClient can use a different base URI on each retry, which is useful when an API is served by several hosts or mirrors. However, the framework configuration couldn't express it, because the base_uri option of scoped clients only accepts a single URI.

Symfony 8.2 adds a retry_failed.base_uris option to list the URIs to fall back to after base_uri, one per retry attempt:

1
2
3
4
5
6
7
8
9
10
11
# config/packages/framework.yaml
framework:
    http_client:
        scoped_clients:
            inventory.client:
                base_uri: 'https://inventory.example.com'
                headers: { 'X-Api-Key': '%env(INVENTORY_API_KEY)%' }
                retry_failed:
                    base_uris:
                        - 'https://inventory-eu.example.com'
                        - 'https://inventory-us.example.com'

The options of the scoped client (the API key in this example) are applied to all the URIs. If you create the clients yourself, the new ScopingHttpClient::forBaseUris() method builds a client scoped to several base URIs at once.

HTTP/2 with Prior Knowledge

Nicolas Grekas
Contributed by Nicolas Grekas in #66557

Servers that speak HTTP/2 over unencrypted connections (h2c), such as gRPC servers, expect clients to use HTTP/2 from the very first byte. This is known as "prior knowledge". Until now, setting the http_version option to 2.0 made the client send an HTTP/1.1 request that offered an upgrade to HTTP/2 on http:// URLs, which is not what those servers expect.

In Symfony 8.2, an explicit http_version: 2.0 means "use HTTP/2, no matter what" in both CurlHttpClient and AmpHttpClient:

1
2
3
4
5
6
7
8
use Symfony\Component\HttpClient\HttpClient;

$client = HttpClient::create(['http_version' => '2.0']);

// this request uses HTTP/2 with prior knowledge
$response = $client->request('POST', 'http://127.0.0.1:50051/inventory.Stock/Check', [
    // ...
]);

Caution

This is a BC break: when http_version is 2.0, servers that only speak HTTP/1.1 are no longer reachable. This also applies to https:// URLs when using AmpHttpClient or cURL 8.10 or higher. Remove the option for those servers to let the client negotiate the best version.

Streams and Closures in HttpOptions::buffer()

Nicolas Grekas
Contributed by Nicolas Grekas in #65127

The buffer request option accepts a boolean, a stream resource where the response body is written, or a closure that decides based on the response headers. However, the buffer() method of the HttpOptions builder only accepted booleans. In Symfony 8.2, it accepts the three of them:

1
2
3
4
5
6
use Symfony\Component\HttpClient\HttpOptions;

$options = (new HttpOptions())
    // buffer only JSON responses
    ->buffer(fn (array $headers): bool => str_contains($headers['content-type'][0] ?? '', 'json'))
    ->toArray();

If you extend HttpOptions and override the buffer() method, update the type of its argument from bool to mixed.

Redirects from HTTPS to HTTP Are No Longer Followed

Nicolas Grekas
Contributed by Nicolas Grekas in #66923

When a server responds to an https:// request with a redirect to an http:// URL, following it sends your custom headers (and the request body on 307 and 308 redirects) in clear text. Also, anyone on the network path could have modified the response that you get.

That's why in Symfony 8.2 the HTTP client no longer follows redirects from HTTPS to HTTP. It returns the 3xx response instead and stores the target URL in the redirect_url info:

1
2
3
4
5
6
7
8
9
$response = $client->request('GET', 'https://example.com/old-page');

if (3 === intdiv($response->getStatusCode(), 100)) {
    // e.g. 'http://example.com/new-page'
    $targetUrl = $response->getInfo('redirect_url');

    // if you trust the target, request it yourself
    $response = $client->request('GET', $targetUrl);
}

This is a BC break, but it only affects downgrading redirects. All the other redirects, including those from HTTP to HTTPS, are followed as before.

Published in #Living on the edge