PHPackages                             imcanugur/fly-http - 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. imcanugur/fly-http

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

imcanugur/fly-http
==================

PSR-18 compliant, middleware-based HTTP client library for enterprise applications

00PHPCI failing

Since Jan 6Pushed 4mo agoCompare

[ Source](https://github.com/imcanugur/fly-http)[ Packagist](https://packagist.org/packages/imcanugur/fly-http)[ RSS](/packages/imcanugur-fly-http/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependenciesVersions (1)Used By (0)

Fly HTTP Client
===============

[](#fly-http-client)

A PSR-18 compliant, middleware-based HTTP client library designed for enterprise applications. Built to compete with Guzzle while providing superior architecture for complex HTTP workflows.

[![Latest Version](https://camo.githubusercontent.com/ec6c29ea5dff2906a62d90b2e544c7430676acfcdeb4bac18e536d7d521b41d3/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f696d63616e756775722f666c792d687474702e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/imcanugur/fly-http)[![License](https://camo.githubusercontent.com/3f9ac1ff93d738fc8b963f4efcf076d669c7cdb79beb496000a00210da2ca0f9/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f696d63616e756775722f666c792d687474702e7376673f7374796c653d666c61742d737175617265)](LICENSE)[![PHP Version](https://camo.githubusercontent.com/5953dede692fb86a346611b07ed6ed8dda5faef912ceb70fc769d58c3f2ac3c5/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f696d63616e756775722f666c792d687474702e7376673f7374796c653d666c61742d737175617265)](https://php.net)[![PSR-18](https://camo.githubusercontent.com/bf85066e37b5c528cd2c8a6bfd5d8e6ef9434897503d3288de4c3d60fa7108ef/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5053522d31382d626c75652e7376673f7374796c653d666c61742d737175617265)](https://www.php-fig.org/psr/psr-18/)

---

🎯 Purpose
---------

[](#-purpose)

Fly HTTP Client is not just a "helper for making HTTP requests." It provides a core HTTP traffic management system for enterprise applications.

The library focuses on architectural correctness, maintainability, and extensibility rather than feature bloat.

---

⚡ Key Features
--------------

[](#-key-features)

- **PSR-18 Compliant**: Drop-in replacement for any PSR-18 HTTP client
- **Zero Dependencies**: Only requires PSR interfaces - no Guzzle, no external libraries
- **Middleware Pipeline**: Chain policies for retry, authentication, logging, caching, circuit breaker
- **Transport Abstraction**: Switch between native cURL, mock, or custom transports
- **Built-in PSR-7**: Complete HTTP message implementation included
- **Enterprise Ready**: Circuit breaker, metrics, caching for production systems
- **Immutable Requests**: Thread-safe, predictable request handling

---

🏗️ Architecture Overview
------------------------

[](#️-architecture-overview)

HTTP processing is divided into three distinct layers:

### 1. Client Layer (Orchestration)

[](#1-client-layer-orchestration)

- Executes the middleware pipeline
- Delegates to transport for actual HTTP calls
- Implements PSR-18 `ClientInterface`
- Manages business logic flow

### 2. Middleware Layer (Policy)

[](#2-middleware-layer-policy)

- Applies cross-cutting concerns
- Can modify requests immutably
- Observes and logs responses
- Handles errors and recovery
- Never makes HTTP calls directly

### 3. Transport Layer (Execution)

[](#3-transport-layer-execution)

- Executes actual HTTP requests
- Can use Guzzle, native curl, or custom implementations
- Completely abstracted from client logic
- Enables testing and vendor flexibility

---

🔗 Middleware System
-------------------

[](#-middleware-system)

Middlewares form a processing pipeline:

```
Request
  ↓
RetryMiddleware    (handles failures)
  ↓
LoggerMiddleware   (logs requests/responses)
  ↓
AuthMiddleware     (adds authentication)
  ↓
Transport          (Guzzle/Native/Custom)
  ↓
Response
```

Each middleware:

- Receives a `RequestInterface` and `$next` callable
- Can modify the request immutably
- Calls `$next($request)` to continue the pipeline
- Can observe and process the response

### Built-in Middlewares

[](#built-in-middlewares)

- **RetryMiddleware**: Exponential backoff retry logic
- **LoggerMiddleware**: PSR-3 compatible request/response logging
- **AuthMiddleware**: Bearer token, Basic auth, custom auth strategies
- **TimeoutMiddleware**: Request and connection timeouts

---

🚀 Basic Usage
-------------

[](#-basic-usage)

```
use Fly\Http\Client;
use Fly\Http\Transport\NativeCurlTransport;
use Fly\Http\Middleware\RetryMiddleware;
use Fly\Http\Middleware\LoggerMiddleware;

// Create transport (zero dependencies!)
$transport = new NativeCurlTransport();

// Create client
$client = new Client($transport);

// Add middlewares
$client->addMiddleware(new RetryMiddleware(3, 1.0));
$client->addMiddleware(new LoggerMiddleware($logger));

// Make request
$response = $client->sendRequest($request);
```

⚙️ Advanced Configuration
-------------------------

[](#️-advanced-configuration)

### Circuit Breaker for Fault Tolerance

[](#circuit-breaker-for-fault-tolerance)

```
use Fly\Http\Middleware\CircuitBreakerMiddleware;
use Symfony\Component\Cache\Adapter\FilesystemAdapter;

// Create cache for circuit breaker state
$cache = new FilesystemAdapter();

// Add circuit breaker middleware
$client->addMiddleware(new CircuitBreakerMiddleware(
    $cache,
    'api-service',  // Service identifier
    5,              // Failure threshold
    60,             // Recovery timeout (seconds)
    3               // Success threshold for half-open
));
```

### Request Caching

[](#request-caching)

```
use Fly\Http\Middleware\CacheMiddleware;
use Symfony\Component\Cache\Adapter\FilesystemAdapter;

// Create cache for HTTP responses
$cache = new FilesystemAdapter();

// Add caching middleware
$client->addMiddleware(new CacheMiddleware(
    $cache,
    300  // TTL in seconds
));
```

### Metrics &amp; Monitoring

[](#metrics--monitoring)

```
use Fly\Http\Middleware\MetricsMiddleware;

// Add metrics collection
$client->addMiddleware(new MetricsMiddleware($logger, 'api-client'));

// Later, get metrics snapshot
$metrics = $client->getMetrics();
$prometheusOutput = $client->exportMetrics();
```

### Authentication &amp; Timeouts

[](#authentication--timeouts)

```
use Fly\Http\Middleware\AuthMiddleware;
use Fly\Http\Middleware\TimeoutMiddleware;

// Authentication
$client->addMiddleware(new AuthMiddleware('your-token', 'Bearer'));

// Timeouts
$client->addMiddleware(new TimeoutMiddleware(30.0, 10.0));
```

🧪 Testing
---------

[](#-testing)

```
use Fly\Http\Client;
use Fly\Http\Transport\MockTransport;

// Create mock transport for testing
$mockTransport = new MockTransport();
$client = new Client($mockTransport);

// Add predefined responses
$mockTransport->addResponse($successResponse);
$mockTransport->addResponse($errorResponse);

// Or use response factory
$mockTransport->setResponseFactory(function ($request) {
    return new Response(200, [], 'OK');
});

// Test your HTTP logic
$response = $client->sendRequest($request);

// Assert requests were made
$mockTransport->assertRequestMade('GET', 'https://api.example.com/users');
```

📋 PSR-7 HTTP Messages
---------------------

[](#-psr-7-http-messages)

Fly includes its own PSR-7 implementation for zero dependencies:

```
use Fly\Http\Http\RequestFactory;
use Fly\Http\Http\ResponseFactory;
use Fly\Http\Http\StreamFactory;
use Fly\Http\Http\UriFactory;

// Create PSR-17 factories
$requestFactory = new RequestFactory();
$responseFactory = new ResponseFactory();
$streamFactory = new StreamFactory();
$uriFactory = new UriFactory();

// Create messages
$request = $requestFactory->createRequest('GET', 'https://api.example.com');
$response = $responseFactory->createResponse(200);
$stream = $streamFactory->createStream('Hello World');
$uri = $uriFactory->createUri('https://api.example.com');
```

🚨 Error Handling
----------------

[](#-error-handling)

```
use Fly\Http\Exception\CircuitBreakerException;

try {
    $response = $client->sendRequest($request);
} catch (CircuitBreakerException $e) {
    // Circuit breaker is open
    echo "Service unavailable: " . $e->getServiceKey();
} catch (\Psr\Http\Client\ClientExceptionInterface $e) {
    // HTTP client error
    echo "HTTP Error: " . $e->getMessage();
}
```

🚚 Transport Options
-------------------

[](#-transport-options)

Transport abstraction allows switching implementations:

```
// Production - Native cURL (recommended)
$client = new Client(new NativeCurlTransport());

// Testing - Mock
$client = new Client(new MockTransport());

// Development - With custom options
$client = new Client(new NativeCurlTransport([
    CURLOPT_TIMEOUT => 60,
    CURLOPT_SSL_VERIFYPEER => false, // Development only!
]));
```

⚡ Performance Tips
------------------

[](#-performance-tips)

1. **Use NativeCurlTransport** for best performance
2. **Enable caching** for repeated requests
3. **Configure circuit breakers** for resilient systems
4. **Set appropriate timeouts** to prevent hanging
5. **Use connection pooling** in high-throughput scenarios

---

📋 PSR Compliance
----------------

[](#-psr-compliance)

The library adheres to established PHP standards:

- **PSR-18**: HTTP Client interface
- **PSR-7**: HTTP Messages (Request/Response)
- **PSR-3**: Logger interface
- **PSR-17**: HTTP Factories

This ensures compatibility across frameworks and prevents vendor lock-in.

---

🎯 When to Use
-------------

[](#-when-to-use)

Use Fly HTTP Client when you need:

- **Complex HTTP workflows** with multiple policies
- **Enterprise applications** requiring audit trails
- **Microservices** with circuit breaker patterns
- **Testable HTTP code** with transport abstraction
- **Framework agnostic** HTTP client

Do not use for:

- Simple one-off HTTP calls
- Basic REST API consumption
- Applications without complex HTTP requirements

---

📦 Installation
--------------

[](#-installation)

```
composer require imcanugur/fly-http
```

---

🤝 Contributing
--------------

[](#-contributing)

We welcome contributions! If you have a feature idea or a bug fix:

1. **Fork** the repository.
2. Create a new **branch** (`git checkout -b feature/YourFeature`).
3. **Commit** your changes using [Conventional Commits](.github/workflows/conventional-commits.md).
4. **Push** to the branch.
5. Open a **Pull Request**.

For bugs and suggestions, please **[open an issue](https://github.com/imcanugur/fly-http/issues)**.

### Commit Convention

[](#commit-convention)

This project uses [Conventional Commits](https://conventionalcommits.org/) for automatic versioning:

```
# Feature (minor version bump)
git commit -m "feat: add new middleware"

# Bug fix (patch version bump)
git commit -m "fix: resolve memory leak"

# Breaking change (major version bump)
git commit -m "feat!: remove deprecated API"
```

### Automatic Versioning

[](#automatic-versioning)

#### GitHub Actions (CI/CD) - Composite Actions

[](#github-actions-cicd---composite-actions)

When you push to the `main` branch, GitHub Actions uses custom composite actions:

```
# Uses ./.github/actions/version-bump
# Uses ./.github/actions/create-tag
# Uses ./.github/actions/packagist-update
```

**Process:**

1. **Version Bump Action**: Analyzes conventional commits → determines version bump
2. **Create Tag Action**: Updates files, commits changes, creates git tag
3. **Packagist Update Action**: Triggers Packagist package update

#### Using Composite Actions Manually

[](#using-composite-actions-manually)

You can also use the actions in other workflows:

```
- name: Bump version
  uses: ./.github/actions/version-bump
  with:
    bump_type: auto

- name: Create tag
  uses: ./.github/actions/create-tag
  with:
    version: ${{ steps.bump.outputs.new_version }}

- name: Update Packagist
  uses: ./.github/actions/packagist-update
  with:
    api_token: ${{ secrets.PACKAGIST_API_TOKEN }}
    username: imcanugur
```

#### Local Development (CI-Independent)

[](#local-development-ci-independent)

For local development or other CI systems, use the release script:

```
# Setup git hooks for automatic release prompts
php bin/setup-hooks

# Manual release commands
php bin/release --auto     # Auto-determine version bump
php bin/release patch      # Manual patch bump (1.0.0 → 1.0.1)
php bin/release minor      # Manual minor bump (1.0.0 → 1.1.0)
php bin/release major      # Manual major bump (1.0.0 → 2.0.0)

# Git hooks will prompt for releases on main branch commits
git add .
git commit -m "feat: add new middleware"
# Hook will ask: "Trigger automatic release?"
```

#### Conventional Commits

[](#conventional-commits)

The system uses [Conventional Commits](https://conventionalcommits.org/) specification:

```
feat: add new feature          # → minor version bump
fix: resolve bug               # → patch version bump
feat!: breaking change         # → major version bump
docs: update docs             # → no version bump
```

---

📄 License
---------

[](#-license)

MIT License - see [LICENSE](LICENSE) file for details.

---

**Enterprise-grade HTTP client built for production systems**

###  Health Score

18

—

LowBetter than 8% of packages

Maintenance52

Moderate activity, may be stable

Popularity0

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity12

Early-stage or recently created project

 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.

### Community

Maintainers

![](https://www.gravatar.com/avatar/2a3bb18c9e573031d4fa9f4cbc66d0083138ff66fe33f65cf33d6728829c698f?d=identicon)[canugur](/maintainers/canugur)

---

Top Contributors

[![imcanugur](https://avatars.githubusercontent.com/u/75624719?v=4)](https://github.com/imcanugur "imcanugur (7 commits)")

### Embed Badge

![Health badge](/badges/imcanugur-fly-http/health.svg)

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

###  Alternatives

[friendsofsymfony/rest-bundle

This Bundle provides various tools to rapidly develop RESTful API's with Symfony

2.8k73.3M317](/packages/friendsofsymfony-rest-bundle)[php-http/discovery

Finds and installs PSR-7, PSR-17, PSR-18 and HTTPlug implementations

1.3k309.5M1.2k](/packages/php-http-discovery)[nyholm/psr7

A fast PHP7 implementation of PSR-7

1.3k235.4M2.4k](/packages/nyholm-psr7)[pusher/pusher-php-server

Library for interacting with the Pusher REST API

1.5k94.8M292](/packages/pusher-pusher-php-server)[spatie/crawler

Crawl all internal links found on a website

2.8k16.3M52](/packages/spatie-crawler)[react/http

Event-driven, streaming HTTP client and server implementation for ReactPHP

78126.4M414](/packages/react-http)

PHPackages © 2026

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