HTTP client

Request

The Symfony HTTP client calls outside APIs from your code. Inject HttpClientInterface into a service, call request() with a method and a URL, and you get a response object back. Nothing is downloaded until you read from it, so the call stays lazy and cheap.

use Symfony\Contracts\HttpClient\HttpClientInterface; class WeatherReader { public function __construct(private HttpClientInterface $client) { } public function current(string $city): array { $response = $this->client->request("GET", "https://api.example.com/weather", [ "query" => ["city" => $city], ]); return $response->toArray(); } }

Decode JSON

Call toArray() to decode a JSON answer into a PHP array in one step. It throws when the status is not successful or the body is not valid JSON, so check the status code first and handle the failure path before touching the data.

$status = $response->getStatusCode(); if ($status !== 200) { throw new \RuntimeException("Weather API answered " . $status); } $data = $response->toArray(); $temp = $data["temp"] ?? null;

Timeouts

One slow API must never freeze your page. Pass a timeout for a single wait and a max_duration for the whole call, and pick numbers that fit the page: a few seconds for interactive pages, longer for background workers.

$response = $this->client->request("GET", "https://api.example.com/weather", [ "timeout" => 5.0, "max_duration" => 10.0, ]);

Retry sketch

The client has no built-in retry, so wrap the call in a tiny loop for transport errors. Sleep briefly between tries and give up after three attempts, so a short outage heals itself while a real failure still reaches your logs.

use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface; $attempts = 0; while (true) { try { return $this->reader->current("Paris"); } catch (TransportExceptionInterface $e) { $attempts++; if ($attempts >= 3) { throw $e; } sleep(1); } }

Next: Scheduler

Article author: Arthur Isaev