The Instructor HTTP client API is part of the Instructor library (https://instructorphp.com) and is bundled with it.You can install it separately via Composer:
The Instructor HTTP client API requires at least one of the supported HTTP client libraries. Depending on which client you want to use, you’ll need to install the corresponding package:For Guzzle:
Copy
composer require guzzlehttp/guzzle
For Symfony HTTP Client:
Copy
composer require symfony/http-client
For Laravel HTTP Client:
The Laravel HTTP Client is included with the Laravel framework. If you’re using Laravel, you don’t need to install it separately.
<?phpuse Cognesy\Http\HttpClient;// Create client with specific configuration$client = HttpClient::using('guzzle');// Or create with debug enabled$client = (new HttpClientBuilder()) ->withPreset('guzzle') ->withDebugPreset('on') ->create();
Here’s an example of making a GET request to fetch data:
Copy
use Cognesy\Http\HttpClient;use Cognesy\Http\Data\HttpRequest;use Cognesy\Http\Exceptions\HttpRequestException;// Create a default HTTP client$client = HttpClient::default();// Create a GET request with query parameters$request = new HttpRequest( url: 'https://api.example.com/users?page=1&limit=10', method: 'GET', headers: [ 'Accept' => 'application/json', 'Authorization' => 'Bearer ' . $apiToken, ], body: [], options: []);try { // Send the request $response = $client->withRequest($request)->get(); // Process the response if ($response->statusCode() === 200) { $data = json_decode($response->body(), true); $users = $data['users'] ?? []; echo "Retrieved " . count($users) . " users:\n"; foreach ($users as $user) { echo "- {$user['name']} ({$user['email']})\n"; } } else { echo "Error: Unexpected status code {$response->statusCode()}\n"; echo "Response: {$response->body()}\n"; }} catch (HttpRequestException $e) { echo "Request failed: {$e->getMessage()}\n";}
These examples demonstrate the basic usage of the Instructor HTTP client API for common HTTP operations. In the following chapters, we’ll explore more advanced features and customization options.