HttpClient Component

Syntax

use Symfony\Component\HttpClient\HttpClient;

response = $httpClient->request(‘GET’, ‘https://api.github.com/repos/symfony/symfony-docs’);

response->getStatusCode();
// content = content = ’{“id”:521583, “name”:“symfony-docs”, …}’
response->toArray();
// transforms the response JSON content into a PHP array
// $content = [‘id’ => 521583, ‘name’ => ‘symfony-docs’, …]

// the response of this request will be a 403 HTTP error
httpClient->request(‘GET’, ‘https://httpbin.org/status/403’);

// this code results in a Symfony\Component\HttpClient\Exception\ClientException
// because it doesn’t check the status code of the response
response->getContent();

// do this instead
if (200 !== response->getStatusCode()) { // handle the HTTP request error (e.g. retry the request) } else { content = $response->getContent();
}