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.0.2(1mo ago)11[1 PRs](https://github.com/philiprehberger/php-api-response/pulls)MITPHPPHP ^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)[ RSS](/packages/philiprehberger-php-api-response/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (3)Versions (3)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)[![License](https://camo.githubusercontent.com/b75bdada327c3fa7a0ca779ca22c250287e774d5d17c81e3eee1aa87d4eb9552/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f7068696c69707265686265726765722f7068702d6170692d726573706f6e7365)](LICENSE)

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();
// {"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}

// 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);
}
```

### 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::paginated($items, $total, $page, $perPage)`200Paginated list with metadataDevelopment
-----------

[](#development)

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

License
-------

[](#license)

MIT

###  Health Score

38

—

LowBetter than 85% of packages

Maintenance89

Actively maintained with recent releases

Popularity4

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity47

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

Every ~4 days

Total

2

Last Release

53d 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 (7 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 响应数据结构。

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

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

2425.9k1](/packages/jsor-hal-client)[elao/json-http-form-bundle

Adds support of JSON requests for Forms

356.0k](/packages/elao-json-http-form-bundle)

PHPackages © 2026

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