Making HTTP requests (e.g. to third-party APIs) is a frequent need for developers working on web applications. In Symfony 4.3 we'll make this simpler with a brand new component called HttpClient.

Basic usage¶

The Symfony\Component\HttpClient\HttpClient class provided to make HTTP requests is quite straightforward:

1 2 3 4 use Symfony\Component\HttpClient\HttpClient ; $httpClient = HttpClient :: create (); $response = $httpClient -> request ( 'GET' , 'https://api.github.com/repos/symfony/symfony-docs' );

A significant difference with other existing HTTP clients is that the request() call is not blocking. In other words, the $response object is available immediately and the code execution can continue.

Later, when you call to getStatusCode() , the code execution will stop until the headers are available and when you call to getContent() , it will stop until the full contents are available (but you can use Streaming responses):

1 2 3 4 5 6 7 8 $statusCode = $response -> getStatusCode (); // $statusCode = 200 $content = $response -> getContent (); // returns the raw content returned by the server (JSON in this case) // $content = '{"id":521583, "name":"symfony-docs", ...}' $content = $response -> toArray (); // transforms the response JSON content into a PHP array // $content = ['id' => 521583, 'name' => 'symfony-docs', ...]

Thanks to this non-blocking behavior, you can make multiple calls to request() to perform parallel requests and then access the info of the responses only after starting all requests.

By default, the component uses native PHP functions to make the HTTP requests, so you don't have to install any other dependency. However, it will use the cURL based transport if your system has both the cURL library and the PHP cURL extension installed.

When the HTTP status code of the response is not in the 200-299 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: