PHPackages                             ayd/api-response-base - 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. ayd/api-response-base

ActiveLibrary[API Development](/categories/api)

ayd/api-response-base
=====================

An base API response package for Hyperf or Laravel applications at AYD Company.

v1.1.0(yesterday)01↑2900%3MITPHPPHP ^8.1

Since Jun 18Pushed yesterdayCompare

[ Source](https://github.com/AYDcompany/api-response-base)[ Packagist](https://packagist.org/packages/ayd/api-response-base)[ RSS](/packages/ayd-api-response-base/feed)WikiDiscussions master Synced today

READMEChangelog (3)DependenciesVersions (4)Used By (3)

API Response Base
=================

[](#api-response-base)

Framework-agnostic JSON API response builder. Provides a consistent response envelope with support for pagination metadata, abilities, and request tracing.

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

[](#installation)

```
composer require ayd/api-response-base
```

Response Envelope
-----------------

[](#response-envelope)

Every response follows this structure:

```
{
    "code": 20001,
    "meta": {
        "abilities": { "create": true, "delete": false },
        "pagination": { "total": 100, "per_page": 20, "current_page": 1 },
        "request_id": "550e8400-e29b-41d4-a716-446655440000"
    },
    "data": {},
    "success": true,
    "message": "Successful"
}
```

The `meta` key is omitted when empty. `data` defaults to `[]` when null. A `request_id` (UUID v4) is always auto-generated.

Usage
-----

[](#usage)

### Building Responses

[](#building-responses)

All methods are static and return arrays:

```
use Ayd\ApiResponseBase\Response;
use Ayd\ApiResponseBase\StatusCode;

// Using convenience methods
$response = Response::ok($data);
$response = Response::created($data, 'Resource created');
$response = Response::noContent();

// Error responses
$response = Response::badRequest('Invalid input', $errors);
$response = Response::unauthorized();
$response = Response::forbidden();
$response = Response::notFound('User not found');
$response = Response::unprocessable('Validation failed', $errors);
$response = Response::internalError();

// Custom status code
$response = Response::build(StatusCode::CREATED, $data, 'Created');
$response = Response::build(418, null, "I'm a teapot");
```

### Using `Meta`

[](#using-meta)

`Meta` is an immutable value object. All setters return new instances:

```
use Ayd\ApiResponseBase\Meta;

// Create with static factories
$meta = Meta::requestId('custom-id');
$meta = Meta::abilities(['create' => true, 'delete' => false]);
$meta = Meta::pagination(total: 100, perPage: 20, currentPage: 1);

// Immutable setters
$meta = $meta->withAbilities(['edit' => true]);
$meta = $meta->withRequestId('another-id');

// Merge two Meta objects (the other wins on conflict)
$merged = $paginationMeta->merge($abilitiesMeta);
```

### Paginator Support

[](#paginator-support)

`Response::build()` automatically detects paginator-like objects via duck typing. Any object implementing `total()`, `perPage()`, `currentPage()`, and `items()` will have its pagination extracted into `meta` and `data` replaced with the items array:

```
// Works with both Laravel's and Hyperf's paginator
$response = Response::ok($paginator);
```

You can also build pagination metadata manually:

```
$meta = Meta::fromPaginator($paginator); // duck-typed
$meta = Meta::pagination(total: 50, perPage: 10, currentPage: 2);
```

### Abilities Resolver

[](#abilities-resolver)

Implement `AbilitiesResolver` to inject authorization flags into every response:

```
use Ayd\ApiResponseBase\Contracts\AbilitiesResolver;

class MyAbilitiesResolver implements AbilitiesResolver
{
    public function resolve(mixed $user = null): array
    {
        return [
            'create' => $user?->can('create') ?? false,
            'delete' => $user?->can('delete') ?? false,
        ];
    }
}
```

### `BuildsApiResponse` Trait

[](#buildsapiresponse-trait)

Provides shared logic for framework-specific implementations:

```
use Ayd\ApiResponseBase\Concerns\BuildsApiResponse;

class MyService
{
    use BuildsApiResponse;

    public function handle()
    {
        $meta = $this->buildMeta();        // auto-generates request_id, auto-resolves abilities
        $meta = $this->resolveAbilitiesMeta($user); // resolve for a specific user
    }
}
```

StatusCode Enum
---------------

[](#statuscode-enum)

```
use Ayd\ApiResponseBase\StatusCode;

StatusCode::OK;                 // 200
StatusCode::CREATED;            // 201
StatusCode::ACCEPTED;           // 202
StatusCode::NO_CONTENT;         // 204
StatusCode::BAD_REQUEST;        // 400
StatusCode::UNAUTHORIZED;       // 401
StatusCode::FORBIDDEN;          // 403
StatusCode::NOT_FOUND;          // 404
StatusCode::UNPROCESSABLE_ENTITY; // 422
StatusCode::INTERNAL_SERVER_ERROR; // 500
```

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

[](#requirements)

- PHP ^8.1

License
-------

[](#license)

MIT

###  Health Score

41

—

FairBetter than 87% of packages

Maintenance100

Actively maintained with recent releases

Popularity2

Limited adoption so far

Community13

Small or concentrated contributor base

Maturity44

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 87.5% 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 ~0 days

Total

3

Last Release

1d ago

### Community

Maintainers

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

---

Top Contributors

[![george-nbi-ad](https://avatars.githubusercontent.com/u/188939767?v=4)](https://github.com/george-nbi-ad "george-nbi-ad (7 commits)")[![jinrenjie](https://avatars.githubusercontent.com/u/5665135?v=4)](https://github.com/jinrenjie "jinrenjie (1 commits)")

### Embed Badge

![Health badge](/badges/ayd-api-response-base/health.svg)

```
[![Health](https://phpackages.com/badges/ayd-api-response-base/health.svg)](https://phpackages.com/packages/ayd-api-response-base)
```

###  Alternatives

[exsyst/swagger

A php library to manipulate Swagger specifications

35916.3M7](/packages/exsyst-swagger)[hubspot/api-client

Hubspot API client

24015.5M18](/packages/hubspot-api-client)[botman/driver-telegram

Telegram driver for BotMan

93452.6k6](/packages/botman-driver-telegram)[200mph/tnt-express-connect

TNT ExpressConnect (API) client

2228.2k](/packages/200mph-tnt-express-connect)

PHPackages © 2026

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