PHPackages                             cbaconnier/php-api-factory - 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. [API Development](/categories/api)
4. /
5. cbaconnier/php-api-factory

ActiveLibrary[API Development](/categories/api)

cbaconnier/php-api-factory
==========================

A fluent PHP library for generating fake API response data

1.0.1(7mo ago)0251MITPHPPHP ^8.3CI passing

Since Oct 15Pushed 7mo agoCompare

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

READMEChangelog (2)Dependencies (4)Versions (2)Used By (0)

PHP API Factory
===============

[](#php-api-factory)

A fluent PHP library for generating fake API response data. Perfect for testing and creating mock API responses.

Inspired by [Laravel's Eloquent Factories](https://laravel.com/docs/12.x/eloquent-factories).

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

[](#installation)

```
composer require --dev cbaconnier/php-api-factory
```

Basic Usage
-----------

[](#basic-usage)

Create a factory by extending `ApiFactory` and defining your data structure:

```
use Cbaconnier\PhpApiFactory\ApiFactory;

class UserApiFactory extends ApiFactory
{
    // optional
    protected ?string $wrapper = 'users';

    protected function definition(): array
    {
        return [
            'id' => $this->faker->unique()->randomNumber(8),
            'name' => $this->faker->name(),
            'email' => $this->faker->unique()->email(),
            'role' => $this->faker->randomElement(['admin', 'member', 'viewer']),
            'created_at' => $this->faker->dateTime()->format('Y-m-d H:i:s'),
        ];
    }
}
```

Generate data:

```
// Single item
$user = UserApiFactory::new()->make();
// ['id' => 12345678, 'name' => 'John Doe', ...]

// Multiple items
$users = UserApiFactory::new()->count(5)->make();
// [['id' => 1, ...], ['id' => 2, ...], ...]

// Wrapped response
$response = UserApiFactory::new()->count(5)->wrap()->make();
// ['users' => [['id' => 1, ...], ['id' => 2, ...]]]
```

Features
--------

[](#features)

### Override Attributes

[](#override-attributes)

```
$user = UserApiFactory::new()->make(['name' => 'Jane Doe', 'role' => 'admin']);
```

### States

[](#states)

Define reusable modifications:

```
class UserApiFactory extends ApiFactory
{
    public function admin(): static
    {
        return $this->state(['role' => 'admin']);
    }

    public function suspended(): static
    {
        return $this->state([
            'status' => 'suspended',
            'suspended_at' => $this->faker->dateTime()->format('Y-m-d H:i:s'),
        ]);
    }
}

$admin = UserApiFactory::new()->admin()->make();
$suspendedAdmin = UserApiFactory::new()->admin()->suspended()->make();
```

### Sequences

[](#sequences)

Generate unique values for each item:

```
$users = UserApiFactory::new()
    ->count(3)
    ->sequence(fn($index) => ['name' => "User {$index}"])
    ->make();
// [['name' => 'User 0', ...], ['name' => 'User 1', ...], ...]

// Cycle through values
$users = UserApiFactory::new()
    ->count(4)
    ->sequence([
        ['role' => 'admin'],
        ['role' => 'member'],
        ['role' => 'viewer'],
    ])
    ->make();
// Roles: admin, member, viewer, admin
```

### Field Filtering

[](#field-filtering)

```
// Only specific fields
$user = UserApiFactory::new()->only(['id', 'name'])->make();

// Exclude specific fields
$user = UserApiFactory::new()->except(['email', 'created_at'])->make();
```

### Recycle Data

[](#recycle-data)

Reuse data from existing collections:

```
$projects = [['id' => 1], ['id' => 2]];

$tasks = TaskFactory::new()
    ->count(10)
    ->recycle($projects, 'project_id')
    ->make();
// Each task gets a random project_id (1 or 2)

// With custom source key
$users = [['user_id' => 100], ['user_id' => 200]];
TaskFactory::new()
    ->recycle($users, 'assigned_to', 'user_id')
    ->make();

// With callable for complex relationships
TaskFactory::new()
    ->recycle($projects, fn($project) => [
        'project' => [
            'id' => $project['id'],
            'name' => $project['name']
        ]
    ])
    ->make();
```

### Nested Factories

[](#nested-factories)

Create complex nested structures:

```
$project = ProjectFactory::new()
    ->has('owner', UserApiFactory::new())
    ->has('tasks', TaskFactory::new()->count(5))
    ->make();
// {
//   'id': 1,
//   'name': 'Project Alpha',
//   'owner': {'id': 1, 'name': 'John Doe', ...},
//   'tasks': [{'id': 1, ...}, {'id': 2, ...}, ...]
// }

// Deep nesting
ProjectFactory::new()
    ->has('tasks',
        TaskFactory::new()
            ->count(3)
            ->has('assignee', UserApiFactory::new())
    )
    ->make();
```

### Metadata

[](#metadata)

Add pagination or other metadata:

```
ApiFactory::register('default', [
    'metadata' => fn($items) => [
        'pagination' => [
            'total' => count($items),
            'per_page' => 15,
            'current_page' => 1,
        ],
        'meta' => [
          'version' => '1.0',
        ],
    ],
]);
ApiFactory::default('default');

$response = UserApiFactory::new()
    ->count(25)
    ->wrap()
    ->withMetadata()
    ->make();
// {
//   'users': [...],
//   'pagination': {...},
//   'meta': {...},
// }
```

Configuration
-------------

[](#configuration)

Configure global settings:

```
use Cbaconnier\PhpApiFactory\ApiFactory;

ApiFactory::register('default', [
    'faker' => [
        'locale' => 'fr_FR',
        'providers' => [CustomProvider::class],
    ],
    'wrapper' => 'data',
    'metadata' => [
        'meta' => ['version' => '1.0'],
    ],
]);

ApiFactory::default('default');
```

Combining Features
------------------

[](#combining-features)

All features work together:

```
$response = UserApiFactory::new()
    ->count(10)
    ->sequence(fn($i) => ['name' => "User {$i}"])
    ->admin()
    ->only(['id', 'name', 'role'])
    ->wrap()
    ->make();
```

Running tests
-------------

[](#running-tests)

```
composer install
composer test
```

License
-------

[](#license)

MIT

###  Health Score

36

—

LowBetter than 82% of packages

Maintenance64

Regular maintenance activity

Popularity15

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity50

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

216d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/1bee0e4f7b6a50c4f243631fbde06b8697c53dbc4ebb715db587cd7d3a3e0246?d=identicon)[cbaconnier](/maintainers/cbaconnier)

---

Top Contributors

[![cbaconnier](https://avatars.githubusercontent.com/u/4738184?v=4)](https://github.com/cbaconnier "cbaconnier (24 commits)")

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/cbaconnier-php-api-factory/health.svg)

```
[![Health](https://phpackages.com/badges/cbaconnier-php-api-factory/health.svg)](https://phpackages.com/packages/cbaconnier-php-api-factory)
```

###  Alternatives

[sylius/sylius

E-Commerce platform for PHP, based on Symfony framework.

8.4k5.6M651](/packages/sylius-sylius)[knuckleswtf/scribe

Generate API documentation for humans from your Laravel codebase.✍

2.3k12.2M45](/packages/knuckleswtf-scribe)[ovac/idoc

Generate beautiful API documentation from your Laravel application

184477.6k2](/packages/ovac-idoc)[canvural/php-openapi-faker

Library to generate fake data for OpenAPI request/response/schemas.

92395.8k2](/packages/canvural-php-openapi-faker)

PHPackages © 2026

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