PHPackages                             gemvc/http-client - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [HTTP &amp; Networking](/categories/http)
4. /
5. gemvc/http-client

ActiveLibrary[HTTP &amp; Networking](/categories/http)

gemvc/http-client
=================

Multi-Environment PHP HTTP Client Package - Synchronous and Asynchronous API Calls for Apache, Nginx, and Swoole

1.2.1(5mo ago)01011MITPHPPHP ^8.2

Since Jan 18Pushed 5mo agoCompare

[ Source](https://github.com/gemvc/http-client)[ Packagist](https://packagist.org/packages/gemvc/http-client)[ RSS](/packages/gemvc-http-client/feed)WikiDiscussions main Synced today

READMEChangelog (3)Dependencies (3)Versions (6)Used By (1)

[![gemvc_let](https://private-user-images.githubusercontent.com/211101824/537327088-9525e293-6247-4d95-b169-73bb0e24a64d.jpg?jwt=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJnaXRodWIuY29tIiwiYXVkIjoicmF3LmdpdGh1YnVzZXJjb250ZW50LmNvbSIsImtleSI6ImtleTUiLCJleHAiOjE3ODI4MTMxNzQsIm5iZiI6MTc4MjgxMjg3NCwicGF0aCI6Ii8yMTExMDE4MjQvNTM3MzI3MDg4LTk1MjVlMjkzLTYyNDctNGQ5NS1iMTY5LTczYmIwZTI0YTY0ZC5qcGc_WC1BbXotQWxnb3JpdGhtPUFXUzQtSE1BQy1TSEEyNTYmWC1BbXotQ3JlZGVudGlhbD1BS0lBVkNPRFlMU0E1M1BRSzRaQSUyRjIwMjYwNjMwJTJGdXMtZWFzdC0xJTJGczMlMkZhd3M0X3JlcXVlc3QmWC1BbXotRGF0ZT0yMDI2MDYzMFQwOTQ3NTRaJlgtQW16LUV4cGlyZXM9MzAwJlgtQW16LVNpZ25hdHVyZT05OGNiYTczOGNhZTMxNWQ1MzUwMGMzMzAxZDFiYzQxMjcyZTZjM2I0ZmVmMjAyOWQ0NjkzNzllODcxZTdjYmU4JlgtQW16LVNpZ25lZEhlYWRlcnM9aG9zdCZyZXNwb25zZS1jb250ZW50LXR5cGU9aW1hZ2UlMkZqcGVnIn0.331X3RWB3st9X0ir1USX8pKMxwy8XDxnit_wRAia1gw)](https://private-user-images.githubusercontent.com/211101824/537327088-9525e293-6247-4d95-b169-73bb0e24a64d.jpg?jwt=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJnaXRodWIuY29tIiwiYXVkIjoicmF3LmdpdGh1YnVzZXJjb250ZW50LmNvbSIsImtleSI6ImtleTUiLCJleHAiOjE3ODI4MTMxNzQsIm5iZiI6MTc4MjgxMjg3NCwicGF0aCI6Ii8yMTExMDE4MjQvNTM3MzI3MDg4LTk1MjVlMjkzLTYyNDctNGQ5NS1iMTY5LTczYmIwZTI0YTY0ZC5qcGc_WC1BbXotQWxnb3JpdGhtPUFXUzQtSE1BQy1TSEEyNTYmWC1BbXotQ3JlZGVudGlhbD1BS0lBVkNPRFlMU0E1M1BRSzRaQSUyRjIwMjYwNjMwJTJGdXMtZWFzdC0xJTJGczMlMkZhd3M0X3JlcXVlc3QmWC1BbXotRGF0ZT0yMDI2MDYzMFQwOTQ3NTRaJlgtQW16LUV4cGlyZXM9MzAwJlgtQW16LVNpZ25hdHVyZT05OGNiYTczOGNhZTMxNWQ1MzUwMGMzMzAxZDFiYzQxMjcyZTZjM2I0ZmVmMjAyOWQ0NjkzNzllODcxZTdjYmU4JlgtQW16LVNpZ25lZEhlYWRlcnM9aG9zdCZyZXNwb25zZS1jb250ZW50LXR5cGU9aW1hZ2UlMkZqcGVnIn0.331X3RWB3st9X0ir1USX8pKMxwy8XDxnit_wRAia1gw)

gemvc/http-client
=================

[](#gemvchttp-client)

**Multi-Environment PHP HTTP Client Package**
Synchronous and Asynchronous API Calls for Apache, Nginx, and Swoole

Part of [Gemvc , a lightweight PHP Framework for microservices](https://gemvc.de)

Overview
--------

[](#overview)

A framework-independent HTTP client package providing both synchronous and asynchronous API call capabilities. Automatically adapts to your runtime environment (Apache, Nginx, or Swoole) for optimal performance.

Features
--------

[](#features)

- ✅ **Synchronous API calls** with retry logic and SSL support
- ✅ **Asynchronous concurrent requests** with configurable concurrency
- ✅ **Enhanced error handling** with exception storage and classification
- ✅ **Environment-aware execution** - optimized for each runtime (Native Coroutines for Swoole)
- ✅ **Framework-independent** - use in any PHP project
- ✅ **Backward compatible** with GEMVC framework

Installation
------------

[](#installation)

```
composer require gemvc/http-client
```

Requirements
------------

[](#requirements)

- PHP 8.2 or higher
- cURL extension
- OpenSwoole extension (optional, for optimized async in Swoole)

Quick Start
-----------

[](#quick-start)

### Synchronous Client

[](#synchronous-client)

```
use Gemvc\Http\Client\HttpClient;

$client = new HttpClient();
$client->setTimeouts(10, 30)
       ->setRetries(3, 200, [500, 502, 503]);

$response = $client->get('https://api.example.com/users', ['page' => 1]);
$data = $client->post('https://api.example.com/users', ['name' => 'John']);

// Error handling (exceptions enabled by default)
try {
    $response = $client->get('https://api.example.com/data');
} catch (\Gemvc\Http\Client\Exception\NetworkException $e) {
    echo "Network error: {$e->getMessage()}\n";
    if ($e->isDnsError()) {
        echo "DNS resolution failed\n";
    }
}

// Or use error storage (disable exceptions)
$client->throwExceptions(false);
$response = $client->get('https://api.example.com/data');
if ($client->hasErrors()) {
    $error = $client->getLastError();
    echo "Error: {$error->getMessage()}\n";
}
```

### Asynchronous Client

[](#asynchronous-client)

```
use Gemvc\Http\Client\AsyncHttpClient;

$async = new AsyncHttpClient();
$async->setMaxConcurrency(5)
      ->setTimeouts(10, 30);

$async->addGet('users', 'https://api.example.com/users', ['page' => 1])
      ->addGet('posts', 'https://api.example.com/posts', ['limit' => 10])
      ->addPost('create', 'https://api.example.com/create', ['name' => 'Test']);

$results = $async->executeAll();

foreach ($results as $requestId => $result) {
    if ($result['success']) {
        echo "Request {$requestId}: {$result['body']}\n";
    }
}
```

### Fire-and-Forget (Non-Blocking)

[](#fire-and-forget-non-blocking)

```
use Gemvc\Http\Client\AsyncHttpClient;

// Perfect for APM logging, analytics, or background tasks
$apm = new AsyncHttpClient();
$apm->setTimeouts(2, 5)
    ->addPost('apm-log', 'https://apm.example.com/log', [
        'endpoint' => '/api/User/list',
        'duration' => 0.123,
        'status' => 200
    ])
    ->fireAndForget(); // Does NOT block!
```

Environment-Specific Implementations
------------------------------------

[](#environment-specific-implementations)

The package provides environment-specific implementations:

- **HttpClient** - Apache/Nginx synchronous implementation
- **AsyncHttpClient** - Apache/Nginx asynchronous implementation
- **SwooleHttpClient** - Native Swoole implementation using Coroutines (no cURL dependency)

API Reference
-------------

[](#api-reference)

### HttpClient Methods

[](#httpclient-methods)

```
// HTTP Methods
get(string $url, array $queryParams = []): string|false
post(string $url, array $data = []): string|false
put(string $url, array $data = []): string|false
postForm(string $url, array $fields = []): string|false
postMultipart(string $url, array $fields = [], array $files = []): string|false
postRaw(string $url, string $body, string $contentType): string|false

// Configuration
setTimeouts(int $connectTimeout, int $timeout): self
setSsl(?string $cert, ?string $key, ?string $ca = null, bool $verifyPeer = true, int $verifyHost = 2): self
setRetries(int $maxRetries, int $retryDelayMs = 200, array $retryOnHttpCodes = []): self
retryOnNetworkError(bool $retry): self
setUserAgent(string $userAgent): self
throwExceptions(bool $throw): self

// Error Handling
clearErrors(): self
hasErrors(): bool
getErrors(): array
getLastError(): ?HttpClientException
```

### AsyncHttpClient Methods

[](#asynchttpclient-methods)

```
// Request Building
addGet(string $requestId, string $url, array $queryParams = [], array $headers = []): self
addPost(string $requestId, string $url, array $data = [], array $headers = []): self
addPut(string $requestId, string $url, array $data = [], array $headers = []): self
addPostForm(string $requestId, string $url, array $fields = [], array $headers = []): self
addPostMultipart(string $requestId, string $url, array $fields = [], array $files = [], array $headers = []): self
addPostRaw(string $requestId, string $url, string $body, string $contentType, array $headers = []): self

// Execution
executeAll(): array
fireAndForget(): bool
waitForAll(): array

// Configuration
setMaxConcurrency(int $max): self
setTimeouts(int $connectTimeout, int $timeout): self
setSsl(?string $cert, ?string $key, ?string $ca = null, bool $verifyPeer = true, int $verifyHost = 2): self
setUserAgent(string $userAgent): self
onResponse(string $requestId, callable $callback): self
clearQueue(): self
getQueueSize(): int

// Error Handling
clearErrors(): self
hasErrors(): bool
getErrors(): array
getLastError(): ?HttpClientException
```

Framework Integration (GEMVC)
-----------------------------

[](#framework-integration-gemvc)

In GEMVC framework, the package is automatically used via wrapper classes:

```
// Framework automatically selects implementation based on environment
$api = new \Gemvc\Http\ApiCall(); // Uses package internally
$api->get('https://api.example.com/data');
```

The framework provides:

- Environment detection via `WebserverDetector`
- Seamless integration with existing `ApiCall` and `AsyncApiCall` classes
- 100% backward compatibility

Error Handling
--------------

[](#error-handling)

The package provides comprehensive error handling with automatic exception classification:

### Exception Types

[](#exception-types)

- **`HttpClientException`** - Base exception for all HTTP client errors
- **`NetworkException`** - Network-related errors (DNS, connection, SSL, etc.)
- **`TimeoutException`** - Request timeout errors (connection or total timeout)

### Error Storage

[](#error-storage)

All exceptions are automatically stored in the `$errors` array property, allowing you to inspect errors without try-catch blocks:

```
$client = new HttpClient();
$client->throwExceptions(false); // Store errors instead of throwing

$response = $client->get('https://api.example.com/data');

if ($client->hasErrors()) {
    $error = $client->getLastError();
    // Access error details: $error->getUrl(), $error->getHttpCode(), etc.
}
```

### Network Error Classification

[](#network-error-classification)

Network errors are automatically classified by type:

```
try {
    $client->get('https://api.example.com/data');
} catch (NetworkException $e) {
    if ($e->isDnsError()) {
        // DNS resolution failed
    } elseif ($e->isSslError()) {
        // SSL/TLS handshake failed
    } elseif ($e->isConnectionError()) {
        // Connection failed
    }

    // Get error type description
    echo $e->getErrorTypeDescription();
}
```

Testing
-------

[](#testing)

```
composer test
```

Test coverage: **85.30%** with comprehensive error handling tests.

License
-------

[](#license)

MIT License - See LICENSE file for details

Contributing
------------

[](#contributing)

Contributions welcome! Please follow:

- PSR-12 coding standards
- PHPStan Level 9 type safety
- Comprehensive test coverage

---

[GemVC , Lightweight PHP Framework Built for Microservices](https://www.gemvc.de)Made with ❤️ by Ali Khorsandfard

###  Health Score

39

—

LowBetter than 84% of packages

Maintenance72

Regular maintenance activity

Popularity12

Limited adoption so far

Community11

Small or concentrated contributor base

Maturity51

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~2 days

Total

5

Last Release

159d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/e56aef71be22058cb4009cb1ef3b656232c2250df6726d63a812e18fe6f73e3c?d=identicon)[gemvc](/maintainers/gemvc)

---

Top Contributors

[![gemvc](https://avatars.githubusercontent.com/u/211101824?v=4)](https://github.com/gemvc "gemvc (18 commits)")

---

Tags

httpasyncapiclientcurlswoolenginxapachesynchronousmulti-environment

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/gemvc-http-client/health.svg)

```
[![Health](https://phpackages.com/badges/gemvc-http-client/health.svg)](https://phpackages.com/packages/gemvc-http-client)
```

###  Alternatives

[aplus/http-client

Aplus Framework HTTP Client Library

2171.6M1](/packages/aplus-http-client)[vinelab/http

An http library developed for the laravel framework. aliases itself as HttpClient

59302.6k11](/packages/vinelab-http)[e-moe/guzzle6-bundle

Integrates Guzzle 6 into your Symfony application

12262.2k1](/packages/e-moe-guzzle6-bundle)[openapi/openapi-sdk

Minimal and agnostic PHP SDK for Openapi® (https://openapi.com)

171.5k1](/packages/openapi-openapi-sdk)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
