Back to listPHP
Guzzle - HTTP Client
Lv.51168@mukitaro18 playsDec 31, 2025
Guzzle HTTP client for API requests with error handling and JSON parsing.
preview.php
1use GuzzleHttp\Client;2use GuzzleHttp\Exception\RequestException;3use Psr\Http\Message\ResponseInterface;4 5class ApiClient6{7 private Client $client;8 9 public function __construct(string $baseUri)10 {11 $this->client = new Client([12 'base_uri' => $baseUri,13 'timeout' => 30.0,14 'headers' => [15 'Accept' => 'application/json',16 'Content-Type' => 'application/json'17 ]18 ]);19 }20 21 public function fetchData(string $endpoint): array22 {23 try {24 $response = $this->client->get($endpoint);25 return $this->parseResponse($response);26 } catch (RequestException $e) {27 return ['error' => $e->getMessage()];28 }29 }30 31 public function postData(string $endpoint, array $data): array32 {33 $response = $this->client->post($endpoint, [34 'json' => $data35 ]);36 return $this->parseResponse($response);37 }38 39 private function parseResponse(ResponseInterface $response): array40 {41 $body = $response->getBody()->getContents();42 return json_decode($body, true) ?? [];43 }44}Custom problems are not included in rankings