How to reuse a Guzzle client for multiple requests in PHP?

To reuse a Guzzle client for multiple requests in PHP, you can follow these steps:

  1. Install Guzzle using Composer by running the following command in your project directory:
composer require guzzlehttp/guzzle
  1. Import the Guzzle package at the top of your PHP file:
use GuzzleHttp\Client;
  1. Create an instance of the Guzzle client:
$client = new Client();
  1. Now, you can make multiple requests using the same client object. For example, to make a GET request, you can use the get() method:
$response = $client->get('https://api.example.com/endpoint');
  1. You can also pass additional options to the request as an array, like headers or query parameters:
$response = $client->get('https://api.example.com/endpoint', [ 'headers' => [ 'Authorization' => 'Bearer your_token', ], 'query' => [ 'param1' => 'value1', 'param2' => 'value2', ], ]);
  1. To reuse the same client object for subsequent requests, simply call the corresponding method again. For example, you can make a 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.