PHPackages                             philiprehberger/php-api-response - 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. philiprehberger/php-api-response

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

philiprehberger/php-api-response
================================

Standardized API response builder for consistent JSON APIs

v1.2.0(4mo ago)169MITPHPPHP ^8.2CI passing

Since Mar 13Pushed 1mo agoCompare

[ Source](https://github.com/philiprehberger/php-api-response)[ Packagist](https://packagist.org/packages/philiprehberger/php-api-response)[ Docs](https://github.com/philiprehberger/php-api-response)[ GitHub Sponsors](https://github.com/philiprehberger)[ RSS](/packages/philiprehberger-php-api-response/feed)WikiDiscussions main Synced 1w ago

READMEChangelogDependencies (6)Versions (6)Used By (0)

PHP API Response
================

[](#php-api-response)

[![Tests](https://github.com/philiprehberger/php-api-response/actions/workflows/tests.yml/badge.svg)](https://github.com/philiprehberger/php-api-response/actions/workflows/tests.yml)[![Latest Version on Packagist](https://camo.githubusercontent.com/0fb3cf25bd7af21e685de78ed8561eda7836d71824275c029436a8e3da6bad37/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f7068696c69707265686265726765722f7068702d6170692d726573706f6e73652e737667)](https://packagist.org/packages/philiprehberger/php-api-response)[![Last updated](https://camo.githubusercontent.com/4bf2b171ab14e558b1dc488db89cd53c749cb247124a0175957f953823f26486/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6173742d636f6d6d69742f7068696c69707265686265726765722f7068702d6170692d726573706f6e7365)](https://github.com/philiprehberger/php-api-response/commits/main)

Standardized API response builder for consistent JSON APIs.

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

[](#requirements)

- PHP 8.2+

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

[](#installation)

```
composer require philiprehberger/php-api-response
```

Usage
-----

[](#usage)

### Success Responses

[](#success-responses)

```
use PhilipRehberger\ApiResponse\ApiResponse;

// Basic success
$response = ApiResponse::success();
// {"success": true, "message": "OK", "data": null}

// Success with data
$response = ApiResponse::success(['id' => 1, 'name' => 'John']);
// {"success": true, "message": "OK", "data": {"id": 1, "name": "John"}}

// Created
$response = ApiResponse::created(['id' => 42]);
// {"success": true, "message": "Created", "data": {"id": 42}}

// No content
$response = ApiResponse::noContent();

// Accepted (202) — request queued for async processing
$response = ApiResponse::accepted(['job_id' => 'abc-123']);
// {"success": true, "message": "Accepted", "data": {"job_id": "abc-123"}}
// {"success": true, "message": "No Content", "data": null}
```

### Error Responses

[](#error-responses)

```
// Generic error
$response = ApiResponse::error('Something went wrong', 500);
// {"success": false, "message": "Something went wrong", "data": null}

// Not found
$response = ApiResponse::notFound('User not found');
// {"success": false, "message": "User not found", "data": null}

// Unauthorized (401)
$response = ApiResponse::unauthorized('Token expired');

// Forbidden (403)
$response = ApiResponse::forbidden('Insufficient permissions');

// Internal server error (500)
$response = ApiResponse::internalServerError('Database unavailable');

// Validation error
$response = ApiResponse::validationError([
    'email' => ['The email field is required.'],
    'name' => ['The name must be at least 2 characters.'],
]);
// {"success": false, "message": "Validation failed", "data": null, "errors": {"email": [...], "name": [...]}}
```

### Paginated Responses

[](#paginated-responses)

```
$response = ApiResponse::paginated(
    items: $users,
    total: 150,
    page: 2,
    perPage: 25,
);
// {"success": true, "message": "OK", "data": [...], "meta": {"pagination": {"total": 150, "page": 2, "per_page": 25, "last_page": 6}}}
```

### Serialization

[](#serialization)

`ResponsePayload` implements `JsonSerializable` and `Stringable`:

```
$response = ApiResponse::success(['key' => 'value']);

// Convert to array
$array = $response->toArray();

// Convert to JSON string
$json = $response->toJson();
$json = $response->toJson(JSON_PRETTY_PRINT);

// Use with json_encode directly
$json = json_encode($response);

// Cast to string
$string = (string) $response;
```

### Using with Laravel

[](#using-with-laravel)

Return responses directly from controllers by accessing the payload properties:

```
public function index(): JsonResponse
{
    $users = User::paginate(25);

    $payload = ApiResponse::paginated(
        items: $users->items(),
        total: $users->total(),
        page: $users->currentPage(),
        perPage: $users->perPage(),
    );

    return response()->json($payload->toArray(), $payload->statusCode);
}
```

### Fluent Chaining

[](#fluent-chaining)

All `with*` methods return a new `ResponsePayload` instance, keeping the original unchanged:

```
$response = ApiResponse::success(['id' => 1, 'name' => 'John'])
    ->withMeta(['request_id' => 'abc-123', 'version' => '2.0'])
    ->withHeaders(['X-Request-Id' => 'abc-123'])
    ->withStatusCode(202);

// Merge additional metadata onto a paginated response
$response = ApiResponse::paginated($users, total: 150, page: 2, perPage: 25)
    ->withMeta(['cache' => 'hit']);

// Attach pagination to any success response after the fact
$response = ApiResponse::success($users)
    ->withPagination(total: 150, page: 2, perPage: 25);

// Attach headers for use in your framework's response
$payload = ApiResponse::created(['id' => 42])
    ->withHeaders(['Location' => '/users/42']);

return response()->json($payload->toArray(), $payload->statusCode)
    ->withHeaders($payload->headers);
```

### Response Shape

[](#response-shape)

All responses follow a consistent structure:

```
{
    "success": true,
    "message": "OK",
    "data": null,
    "errors": {},
    "meta": {}
}
```

- `success` (bool) - Always present
- `message` (string) - Always present
- `data` (mixed) - Always present
- `errors` (object) - Only present when there are errors
- `meta` (object) - Only present when metadata is provided (e.g., pagination)

API
---

[](#api)

MethodStatus CodeDescription`ApiResponse::success($data, $message)`200Successful response with optional data`ApiResponse::created($data, $message)`201Resource created successfully`ApiResponse::noContent($message)`204Success with no response body`ApiResponse::error($message, $statusCode, $errors)`400Generic error response`ApiResponse::validationError($errors, $message)`422Validation failure with field errors`ApiResponse::notFound($message)`404Resource not found`ApiResponse::unauthorized($message, $errors)`401Authentication required or failed`ApiResponse::forbidden($message, $errors)`403Authenticated but not permitted`ApiResponse::accepted($data, $message)`202Request accepted for asynchronous processing`ApiResponse::internalServerError($message, $errors)`500Unexpected server-side failure`ApiResponse::paginated($items, $total, $page, $perPage)`200Paginated list with metadata### Fluent Methods on `ResponsePayload`

[](#fluent-methods-on-responsepayload)

MethodDescription`withMeta(array $meta)`Returns a new instance with merged metadata`withHeaders(array $headers)`Returns a new instance with custom response headers`withStatusCode(int $code)`Returns a new instance with overridden HTTP status code`withPagination(int $total, int $page, int $perPage)`Returns a new instance with a `pagination` block merged into metaDevelopment
-----------

[](#development)

```
composer install
vendor/bin/phpunit
vendor/bin/pint --test
vendor/bin/phpstan analyse
```

Support
-------

[](#support)

If you find this project useful:

⭐ [Star the repo](https://github.com/philiprehberger/php-api-response)

🐛 [Report issues](https://github.com/philiprehberger/php-api-response/issues?q=is%3Aissue+is%3Aopen+label%3Abug)

💡 [Suggest features](https://github.com/philiprehberger/php-api-response/issues?q=is%3Aissue+is%3Aopen+label%3Aenhancement)

❤️ [Sponsor development](https://github.com/sponsors/philiprehberger)

🌐 [All Open Source Projects](https://philiprehberger.com/open-source-packages)

💻 [GitHub Profile](https://github.com/philiprehberger)

🔗 [LinkedIn Profile](https://www.linkedin.com/in/philiprehberger)

License
-------

[](#license)

[MIT](LICENSE)

###  Health Score

41

—

FairBetter than 87% of packages

Maintenance84

Actively maintained with recent releases

Popularity10

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity51

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 88.9% 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 ~6 days

Total

5

Last Release

124d ago

### Community

Maintainers

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

---

Top Contributors

[![philiprehberger](https://avatars.githubusercontent.com/u/8218077?v=4)](https://github.com/philiprehberger "philiprehberger (16 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (2 commits)")

---

Tags

responsejsonapireststandardized

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

![Health badge](/badges/philiprehberger-php-api-response/health.svg)

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

###  Alternatives

[guanguans/laravel-api-response

Normalize and standardize Laravel API response data structure. - 规范化和标准化 Laravel API 响应数据结构。

486.4k](/packages/guanguans-laravel-api-response)[jsor/hal-client

A lightweight client for consuming and manipulating Hypertext Application Language (HAL) resources.

2226.1k1](/packages/jsor-hal-client)

PHPackages © 2026

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