To reuse a Guzzle client for multiple requests in PHP, you can follow these steps:
composer require guzzlehttp/guzzle
use GuzzleHttp\Client;
$client = new Client();
GET
request, you can use the get()
method:$response = $client->get('https://api.example.com/endpoint');
$response = $client->get('https://api.example.com/endpoint', [
'headers' => [
'Authorization' => 'Bearer your_token',
],
'query' => [
'param1' => 'value1',
'param2' => 'value2',
],
]);
POST
request:$response = $client->post('https://api.example.com/endpoint', [
'json' => [
'name' => 'John Doe',
'email' => '[email protected]',
],
]);
By reusing the Guzzle client object, you can take advantage of persistent connections and other optimization features, resulting in better performance for your PHP requests.