Skip to content

Fetch PHP

The JavaScript fetch API for PHP

Modern, simple HTTP client with a familiar API

Fetch PHP

The Modern HTTP Client for PHP ​

php
// Quick API requests with fetch()
$response = fetch('https://api.example.com/users');
$users = $response->json();

// Or use HTTP method helpers
$user = post('https://api.example.com/users', [
    'name' => 'John Doe',
    'email' => 'john@example.com'
])->json();

Flexible Authentication ​

php
// Bearer token auth
$response = fetch('https://api.example.com/me', [
    'token' => 'your-oauth-token'
]);

// Basic auth
$response = fetch('https://api.example.com/private', [
    'auth' => ['username', 'password']
]);

Powerful Async Support ​

php
// Create promises for parallel requests
$usersPromise = async(function() {
    return fetch('https://api.example.com/users');
});

$postsPromise = async(function() {
    return fetch('https://api.example.com/posts');
});

// Wait for all to complete
all(['users' => $usersPromise, 'posts' => $postsPromise])
    ->then(function ($results) {
        // Process results from both requests
        $users = $results['users']->json();
        $posts = $results['posts']->json();
    });

Modern Await-Style Syntax ​

php
await(async(function() {
    // Process multiple requests in parallel
    $results = await(all([
        'users' => async(fn() => fetch('https://api.example.com/users')),
        'posts' => async(fn() => fetch('https://api.example.com/posts'))
    ]));

    // Work with results as if they were synchronous
    foreach ($results['users']->json() as $user) {
        echo $user['name'] . "\n";
    }
}));

Why Fetch PHP? ​

Fetch PHP brings the simplicity of JavaScript's fetch API to PHP, while adding powerful features like retry handling, promise-based asynchronous requests, and fluent interface for request building. It's designed to be both simple for beginners and powerful for advanced users.

Getting Started ​

bash
composer require jerome/fetch-php

Read the quick start guide to begin working with Fetch PHP.

Created by Jerome Thayananthajothy and released under the MIT License.