PHPackages                             phpmystic/retrofit-php - 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. phpmystic/retrofit-php

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

phpmystic/retrofit-php
======================

A type-safe HTTP client for PHP inspired by Square's Retrofit. Turn your HTTP API into a PHP interface using attributes.

1.5.0(5mo ago)11MITPHPPHP ^8.1

Since Nov 24Pushed 5mo agoCompare

[ Source](https://github.com/mehdilight/retrofit-php)[ Packagist](https://packagist.org/packages/phpmystic/retrofit-php)[ RSS](/packages/phpmystic-retrofit-php/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (8)Versions (2)Used By (0)

Retrofit PHP
============

[](#retrofit-php)

A type-safe HTTP client for PHP, inspired by [Square's Retrofit](https://square.github.io/retrofit/) for Java/Kotlin.

Turn your HTTP API into a PHP interface using attributes.

Features
--------

[](#features)

- ✅ **Type-Safe API Definitions** - Define APIs as PHP interfaces with attributes
- ✅ **HTTP Methods** - Support for GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS
- ✅ **URL Parameters** - Path parameters, query parameters, and query maps
- ✅ **Request Body** - JSON, form-encoded, and multipart requests
- ✅ **Headers** - Static and dynamic headers
- ✅ **Converters** - JSON, XML, and custom converters
- ✅ **DTO Hydration** - Automatic object mapping with nested objects and field name mapping
- ✅ **Async Requests** - Promise-based async operations with Guzzle
- ✅ **Retry Policies** - Automatic retries with exponential backoff
- ✅ **Response Caching** - TTL-based caching with pluggable cache backends
- ✅ **Interceptors** - Request/response modification and logging
- ✅ **Timeouts** - Per-endpoint timeout configuration
- ✅ **File Handling** - Streaming uploads/downloads with progress tracking
- ✅ **PSR-7 &amp; PSR-18 Compliant** - Full PSR standards support
- ✅ **XML Support** - Built-in XML serialization/deserialization
- ✅ **Symfony Serializer** - Advanced serialization with groups and contexts

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

[](#installation)

```
composer require phpmystic/retrofit-php
```

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

[](#quick-start)

### 1. Define your API interface

[](#1-define-your-api-interface)

```
use Phpmystic\RetrofitPhp\Attributes\Http\GET;
use Phpmystic\RetrofitPhp\Attributes\Http\POST;
use Phpmystic\RetrofitPhp\Attributes\Parameter\Path;
use Phpmystic\RetrofitPhp\Attributes\Parameter\Query;
use Phpmystic\RetrofitPhp\Attributes\Parameter\Body;

interface GitHubApi
{
    #[GET('/users/{user}')]
    public function getUser(#[Path('user')] string $username): array;

    #[GET('/users/{user}/repos')]
    public function listRepos(
        #[Path('user')] string $username,
        #[Query('per_page')] int $perPage = 10,
        #[Query('sort')] string $sort = 'updated'
    ): array;

    #[POST('/repos/{owner}/{repo}/issues')]
    public function createIssue(
        #[Path('owner')] string $owner,
        #[Path('repo')] string $repo,
        #[Body] array $issue
    ): array;
}
```

### 2. Create a Retrofit instance

[](#2-create-a-retrofit-instance)

```
use Phpmystic\RetrofitPhp\Retrofit;
use Phpmystic\RetrofitPhp\Http\GuzzleHttpClient;
use Phpmystic\RetrofitPhp\Converter\JsonConverterFactory;

$retrofit = Retrofit::builder()
    ->baseUrl('https://api.github.com')
    ->client(GuzzleHttpClient::create(['timeout' => 30]))
    ->addConverterFactory(new JsonConverterFactory())
    ->build();

// Or use TypedJsonConverterFactory for automatic DTO hydration
use Phpmystic\RetrofitPhp\Converter\TypedJsonConverterFactory;

$retrofit = Retrofit::builder()
    ->baseUrl('https://api.github.com')
    ->client(GuzzleHttpClient::create(['timeout' => 30]))
    ->addConverterFactory(new TypedJsonConverterFactory())  // Enables DTO hydration
    ->build();
```

### 3. Use your API

[](#3-use-your-api)

```
$github = $retrofit->create(GitHubApi::class);

// GET request with path parameter
$user = $github->getUser('octocat');
echo $user['name']; // "The Octocat"

// GET request with query parameters
$repos = $github->listRepos('octocat', perPage: 5, sort: 'stars');

// POST request with body
$issue = $github->createIssue('owner', 'repo', [
    'title' => 'Bug report',
    'body' => 'Something is broken',
]);
```

Documentation
-------------

[](#documentation)

### Core Concepts

[](#core-concepts)

- [HTTP Methods](docs/http-methods.md) - GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS
- [URL Parameters](docs/parameters.md) - Path parameters, query parameters, and query maps
- [Request Body](docs/request-body.md) - JSON, form-encoded, and multipart requests
- [Headers](docs/headers.md) - Static and dynamic header configuration

### Configuration

[](#configuration)

- [HTTP Client Configuration](docs/client-configuration.md) - Guzzle options and custom clients
- [Converters](docs/converters.md) - JSON, XML, Symfony Serializer, DTO hydration, and custom converters
- [Timeouts](docs/timeouts.md) - Per-endpoint timeout configuration

### Advanced Features

[](#advanced-features)

- [Async Requests](docs/async.md) - Promise-based async operations and parallel requests
- [Retry Policies](docs/retry.md) - Automatic retries with backoff strategies
- [Response Caching](docs/caching.md) - TTL-based caching with custom backends
- [Interceptors](docs/interceptors.md) - Request/response modification and logging
- [File Handling](docs/file-handling.md) - Streaming uploads/downloads with progress tracking

### Examples

[](#examples)

- [Complete Examples](docs/examples.md) - Full working examples with all features

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

[](#requirements)

- PHP 8.1+
- Guzzle 7.0+

**Optional Dependencies:**

- PSR-18 HTTP Client: `psr/http-client` and a PSR-18 implementation (e.g., `symfony/http-client`, `nyholm/psr7`)
- XML Support: Built-in (uses PHP's SimpleXML)
- Symfony Serializer: `symfony/serializer` ^6.0 or ^7.0

Support
-------

[](#support)

If you find this project helpful, consider supporting its development!

[ ![Buy Me A Coffee](https://camo.githubusercontent.com/71524ddd3bba85ee4d02e5cb81ae51e264b4b87fa4a699b00e1fd756ef153568/68747470733a2f2f6d65646961342e67697068792e636f6d2f6d656469612f76312e59326c6b505463354d4749334e6a45785a6d646e4f574d78636d356f4e445577626a646e626d383362444e6e636a4233637a55334e7a42766448467a625745785a6a4e3564795a6c634431324d563970626e526c636d35686246396e61575a66596e6c666157516d5933513963772f376b5a45307a35325364397a5345537a44412f67697068792e676966)](https://buymeacoffee.com/phpmystic)[![Buy Me A Coffee](https://camo.githubusercontent.com/e8ded118cb9672c557551f4edf56546f8820de15d3b0cf2b9c4bd2ae713ccad6/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4275792532304d6525323041253230436f666665652d737570706f72742d79656c6c6f772e7376673f7374796c653d666c6174266c6f676f3d6275792d6d652d612d636f66666565)](https://buymeacoffee.com/phpmystic)

License
-------

[](#license)

MIT

###  Health Score

32

—

LowBetter than 72% of packages

Maintenance70

Regular maintenance activity

Popularity3

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity43

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

Unknown

Total

1

Last Release

175d ago

### Community

Maintainers

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

---

Top Contributors

[![mehdilight](https://avatars.githubusercontent.com/u/107317646?v=4)](https://github.com/mehdilight "mehdilight (8 commits)")

---

Tags

apiasyncclientguzzlehttprestretrofitstreamingtype-safehttppsr-7asyncapiclientsymfonyrestxmlhttp clientpsr-18Guzzleserializerstreamingcachemultipartretryfile-uploadtype-safeinterceptorretrofit

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/phpmystic-retrofit-php/health.svg)

```
[![Health](https://phpackages.com/badges/phpmystic-retrofit-php/health.svg)](https://phpackages.com/packages/phpmystic-retrofit-php)
```

###  Alternatives

[react/http

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

78026.4M414](/packages/react-http)[eightpoints/guzzle-bundle

Integrates Guzzle 6.x, a PHP HTTP Client, into Symfony. Comes with easy and powerful configuration options and optional plugins.

45912.1M55](/packages/eightpoints-guzzle-bundle)[amphp/http-client-psr7

PSR-7 adapter for Amp's HTTP client.

1454.7k4](/packages/amphp-http-client-psr7)[e-moe/guzzle6-bundle

Integrates Guzzle 6 into your Symfony application

11259.2k](/packages/e-moe-guzzle6-bundle)[claude-php/claude-php-sdk

A universal, framework-agnostic PHP SDK for the Anthropic Claude API with PSR compliance

13920.7k2](/packages/claude-php-claude-php-sdk)[art4/requests-psr18-adapter

Use WordPress/Requests as a PSR-18 HTTP client

153.3k](/packages/art4-requests-psr18-adapter)

PHPackages © 2026

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