useFetch API¶
New in v2.0.1
Async HTTP requests with parallel execution support
-
Simple & Powerful
Fluent interface for HTTP requests with full async support
-
Highly Configurable
Timeouts, SSL, headers, redirects - everything you need
-
Parallel Execution
True concurrent requests with curl_multi for maximum performance
-
Modern PHP API
Familiar syntax with modern PHP features
Basic Usage¶
Simple GET Request¶
HTTP Methods¶
Configuration Options¶
Chain Before HTTP Method
All configuration methods must be called before ->get(), ->post(), etc.
<?php
$response = useFetch('https://api.example.com/users')
->headers(['Authorization' => 'Bearer token']) // (1)
->timeout(30) // (2)
->connectTimeout(5) // (3)
->verifySSL(true) // (4)
->withCertificate('/path/to/cacert.pem') // (5)
->followRedirects(true, 5) // (6)
->withUserAgent('MyApp/1.0') // (7)
->get();
- Headers - Add custom headers (Authorization, API keys, etc.)
- Timeout - Request timeout in seconds (supports decimals like
0.5) - Connect Timeout - Connection timeout (cURL only)
- SSL Verification - Enable/disable certificate verification
- CA Bundle - Path to custom certificate bundle
- Redirects - Follow redirects with max limit (cURL only)
- User Agent - Custom User-Agent string
Response Handling¶
<?php
$response = useFetch('https://api.example.com/users/2')->get();
$data = $response->json(); // (1)
$text = $response->text(); // (2)
$status = $response->status(); // (3)
$headers = $response->headers(); // (4)
if ($response->ok()) { // (5)
// Success handling
}
if ($response->failed()) { // (6)
echo $response->error(); // (7)
}
- Returns decoded JSON as associative array
- Returns raw response body as string
- Returns HTTP status code (200, 404, etc.)
- Returns response headers as array
- Checks if status is 200-299
- Checks if request failed
- Returns error message string
Asynchronous Requests¶
Requires cURL Extension
Async features only work when cURL is available. Falls back to sync execution otherwise.
Single Async Request¶
<?php
$promise = useFetch('https://api.example.com/users/1')->async()->get();
// Do other work here...
$response = $promise->wait();
echo $response->json()['name'];
Parallel Execution (Recommended)¶
True Concurrency
Execute multiple requests simultaneously using curl_multi for maximum performance!
<?php
use PhpSPA\Core\Client\AsyncResponse;
// Prepare requests
$user = useFetch('https://api.example.com/users/1')->async()->get();
$posts = useFetch('https://api.example.com/posts')->async()->get(['userId' => 1]);
$comments = useFetch('https://api.example.com/comments')->async()->get(['userId' => 1]);
// Execute all simultaneously
[$userRes, $postsRes, $commentsRes] = AsyncResponse::all([
$user, $posts, $comments
]);
echo $userRes->json()['name'];
echo count($postsRes->json()) . " posts";
With Callbacks¶
<?php
useFetch('https://api.example.com/users/1')
->async()
->get()
->then(fn($res) => print $res->json()['name'])
->wait();
Complete Examples¶
POST with Error Handling¶
<?php
$response = useFetch('https://api.example.com/users')
->headers(['Authorization' => 'Bearer token'])
->timeout(15)
->post(['name' => 'Dave', 'email' => 'dave@example.com']);
if ($response->ok()) {
echo "✅ User created: " . $response->json()['id'];
} else {
error_log('❌ API Error: ' . $response->error());
}
Parallel API Calls¶
<?php
use PhpSPA\Core\Client\AsyncResponse;
$requests = [
useFetch('https://api.example.com/users/1')->async()->get(),
useFetch('https://api.example.com/users/2')->async()->get(),
useFetch('https://api.example.com/users/3')->async()->get(),
];
$responses = AsyncResponse::all($requests);
foreach ($responses as $res) {
echo $res->json()['name'] . "\n";
}
Important Notes¶
Avoid Same-Server Requests
Never make HTTP requests to the same server handling the current request - it causes deadlock!
Understanding Async Behavior
PHP is synchronous by nature. The async() method prepares cURL handles without executing them:
- Use
AsyncResponse::all()for true parallel execution withcurl_multi - Sequential
wait()calls execute requests one by one - Parallel execution is significantly faster for multiple requests