Boost PHP API Calls with Guzzle Async Requests: A Step‑by‑Step Guide
This guide explains how to replace slow synchronous HTTP calls with Guzzle's asynchronous requests in PHP, showing code examples, performance measurements, and practical tips for installing and using promises to achieve faster concurrent API calls.
When integrating third‑party APIs, synchronous calls can become a bottleneck; using asynchronous requests allows the script to fire requests without waiting for each response, dramatically improving throughput.
Synchronous Request Example
<?php
declare(strict_types=1);
$url = 'http://127.0.0.1:8888/index/sync';
$timeOne = microtime(true);
foreach (range(1, 100) as $key) {
$list[] = file_get_contents($url);
}
$timeTwo = microtime(true);
echo '[x] [system call duration] ' . ($timeTwo - $timeOne) . PHP_EOL;The loop makes 100 sequential calls and takes about 37.23 seconds.
Concurrent Requests with Guzzle
Guzzle is a PHP HTTP client that simplifies sending requests and can be used for both synchronous and asynchronous operations. Supports building query strings, POST, file upload/download, cookies, JSON payloads, etc. Same API for sync and async calls. Implements PSR‑7 for request/response handling. Abstracts underlying transport, allowing non‑blocking event loops. Middleware system lets you customize client behavior.
Install Guzzle via Composer:
composer require guzzlehttp/guzzleAsync Request Pseudocode
<?php
declare(strict_types=1);
require_once __DIR__ . '/../vendor/autoload.php';
use GuzzleHttp\Client;
use GuzzleHttp\Promise;
$requestData = [
'username' => '开源技术小栈',
'age' => 24
];
$url = 'http://127.0.0.1:8888/index/sync';
$header = ['Authorization' => 'Bearer xxxxxxxxxx'];
$timeOne = microtime(true);
$client = new Client(['verify' => false]);
for ($i = 0; $i < 100; $i++) {
$promises[$i] = $client->postAsync($url, ['headers' => $header, 'json' => $requestData]);
}
$responses = Promise\Utils::unwrap($promises);
foreach ($responses as $key => $response) {
echo "【Response Status】 : " . $response->getStatusCode() . "
";
}
$timeTwo = microtime(true);
echo '[x] [system call duration] ' . ($timeTwo - $timeOne) . PHP_EOL;Running the async version completes 100 requests in roughly 10.41 seconds, with each response returning status code 200.
For more details, refer to the official Guzzle documentation: https://docs.guzzlephp.org/en/stable/quickstart.html
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Open Source Tech Hub
Sharing cutting-edge internet technologies and practical AI resources.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
