# FetchPHP: A Modern PHP HTTP Client with Synchronous & Asynchronous Request Support

By Dinesh Uprety
Published: 2024-12-14
Updated: 2024-12-14
Canonical: https://laranepal.com/blog/fetchphp-a-modern-php-http-client-with-synchronous-asynchronous-request-support

# FetchPHP: A Modern HTTP Client for PHP

**[FetchPHP](https://fetch-php.thavarshan.com/guide/getting-started.html)** is a modern HTTP client for PHP that mimics
the JavaScript `fetch()` API, providing both synchronous and
asynchronous request handling. Whether you're familiar with JavaScript's `fetch()` or Laravel's HTTP client, FetchPHP
provides a similar, intuitive API. It is powered by the Guzzle HTTP client for synchronous requests and Matrix for
asynchronous task management using PHP Fibers.

## Core Features

FetchPHP simplifies HTTP requests in PHP by providing several key features:

* **JavaScript-like** `fetch()` **API**: A familiar interface for developers already accustomed to JavaScript’s fetch()
  API.

* **Fluent API**: Chainable methods for flexible and readable HTTP request construction.

* **Asynchronous Support**: Manage asynchronous tasks seamlessly with PHP Fibers, powered by Matrix.

* **Powered by Guzzle**: Reliable synchronous requests powered by the Guzzle HTTP client.

* **Error Handling**: Robust error management for both synchronous and asynchronous requests.

## Installation

### Prerequisites

Ensure your environment meets the following requirements before installing **`FetchPHP`**:

* **PHP 8.1 or higher**: FetchPHP requires PHP Fibers, introduced in PHP 8.1, so make sure you’re running PHP 8.1 or
  later.

* **Composer**: FetchPHP is distributed via Composer. Ensure Composer is installed in your environment.

### Installing FetchPHP

To install FetchPHP, run the following Composer command:

```bash
composer require jerome/fetch-php
```

This will download and install FetchPHP along with its required dependencies, including **`Guzzle`** for HTTP client
handling
and `Matrix` for asynchronous task management.

### Configuration

FetchPHP uses Guzzle as the underlying HTTP client. You can configure various Guzzle options by passing them into the
fetch() function or by creating a custom Guzzle client. Here are some commonly used configuration options:

### Guzzle Client Options

* **base_uri**: The base URI to use with requests. Example: `https://example.com`.
* **timeout**: Timeout in seconds for the request. Example: `timeout => 5`.
* **connect_timeout**: Timeout in seconds for establishing a connection. Example: `connect_timeout => 2`.
* **allow_redirects**: Controls whether redirects are allowed (can be `true`, `false`, or an array of options; default
  is `true`).

For a complete list of Guzzle configuration options, refer to
the [Guzzle Client Options](https://fetch-php.thavarshan.com/guide/installation.html#guzzle-client-options)
documentation.

### Checking Installation

To confirm FetchPHP is correctly installed, you can create a simple HTTP request using the `fetch()` function:

```php
<?php

$response = fetch('https://example.com');

if ($response->ok()) {
    echo "FetchPHP is working correctly!";
}
```

### Uninstalling FetchPHP

To remove FetchPHP from your project, run:

```bash
composer remove jerome/fetch-php
```

This will uninstall FetchPHP and update your `composer.json` file accordingly.

### Usage Examples

FetchPHP makes it easy to perform synchronous and asynchronous HTTP requests. Below are examples of both.

**Synchronous Example**

```php
<?php

$response = fetch('https://example.com', [
    'method' => 'POST',
    'headers' => [
        'Content-Type' => 'application/json',
    ],
    'body' => json_encode(['key' => 'value']),
]);

$data = $response->json();
```

This example sends a POST request with a JSON body and retrieves the JSON response.

**Asynchronous Example**

FetchPHP also supports asynchronous requests using a syntax similar to JavaScript’s async/await.

```php
<?php
use Fetch\Interfaces\Response as ResponseInterface;

$data = null;

async(fn () => fetch('https://example.com', [
    'method' => 'POST',
    'headers' => [
        'Content-Type' => 'application/json',
    ],
    'body' => json_encode(['key' => 'value']),
]))
    ->then(fn (ResponseInterface $response) => $data = $response->json())  // Success handler
    ->catch(fn (Throwable $e) => $e->getMessage());                // Error handler

echo $data;
```

This example asynchronously sends a POST request and processes the JSON response, or handles an error using `.catch()`.

## Conclusion

FetchPHP is a powerful HTTP client for PHP that simplifies both synchronous and asynchronous requests with an intuitive
API. By mimicking JavaScript’s `fetch()` API, FetchPHP offers a familiar experience for developers. Whether you’re
building a simple API client or a complex web application, FetchPHP can streamline your HTTP request handling in PHP.
