PHPackages                             larahub/api-response-kit - 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. larahub/api-response-kit

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

larahub/api-response-kit
========================

A Laravel package to standardize API responses, errors, and validation outputs across Laravel applications

v1.0.1(3mo ago)02MITPHPPHP ^8.1

Since Jan 27Pushed 2mo agoCompare

[ Source](https://github.com/LaraHubKit/api-response-kit)[ Packagist](https://packagist.org/packages/larahub/api-response-kit)[ Docs](https://www.larahub.io)[ RSS](/packages/larahub-api-response-kit/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (3)Versions (3)Used By (0)

LaraHub API Response Kit
========================

[](#larahub-api-response-kit)

**Vendor:** LaraHub | **Domain:** [larahub.io](https://www.larahub.io) | **Package:** `larahub/api-response-kit`

A Laravel package to standardize API responses, errors, and validation outputs across Laravel applications.

Why
---

[](#why)

- Consistent JSON response schema across teams/projects
- Less boilerplate in controllers/services
- Predictable error + validation formats
- Optional request ID for tracing/debugging
- Environment-aware debug mode (hides sensitive info in production)
- Custom formatter support for project-specific schemas

---

Features
--------

[](#features)

FeatureDescriptionAutomatic response formattingWraps controller return values (arrays, models, collections) into standard JSONPagination supportAuto-detects `paginate()` / `cursorPaginate()` results and moves pagination metadata into `meta.pagination`Global error handlingConverts exceptions into standardized JSON error responses (404, 403, 401, 500, etc.)Validation error standardizationFormats Laravel validation errors into a clean, predictable structureConfigurable response schemaCustomize response keys via config fileRequest ID generationUnique request ID (`LH-XXXXXX`) per request for debugging/loggingFacade supportManual response control when automatic formatting is not neededMiddleware integrationIntercepts outgoing responses and applies formatting automaticallyDebug modeFull stack traces in dev; sensitive info (SQL, file paths) hidden in productionCustom formattersDefine your own response structure via custom formatter classes---

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

[](#installation)

```
composer require larahub/api-response-kit
```

Publish Config
--------------

[](#publish-config)

```
php artisan vendor:publish --tag=api-response-kit-config
```

This will publish `config/api-response-kit.php`.

---

Response Schema
---------------

[](#response-schema)

### Success Response

[](#success-response)

```
{
  "success": true,
  "message": "Success",
  "data": {},
  "meta": {
    "request_id": "LH-XXXXXX",
    "timestamp": "2026-01-27T12:00:00Z"
  }
}
```

### Error Response

[](#error-response)

```
{
  "success": false,
  "message": "Error message",
  "errors": null,
  "meta": {
    "request_id": "LH-XXXXXX",
    "timestamp": "2026-01-27T12:00:00Z"
  }
}
```

### Validation Error Response

[](#validation-error-response)

```
{
  "success": false,
  "message": "Validation failed",
  "errors": {
    "email": "The email field is required"
  },
  "meta": {
    "request_id": "LH-XXXXXX",
    "timestamp": "2026-01-27T12:00:00Z"
  }
}
```

---

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

[](#basic-usage)

When middleware is enabled, normal controller returns are automatically wrapped into the standard response schema.

```
// Controller action — no changes needed
return User::query()->latest()->paginate();
```

---

Pagination
----------

[](#pagination)

### Auto-detection (middleware)

[](#auto-detection-middleware)

When the middleware is enabled, any `paginate()` or `cursorPaginate()` return value is automatically detected and reformatted. No changes needed in the controller:

```
// Default per_page comes from config (default: 10)
return User::query()->latest()->paginate();

// Developer-defined per_page
return User::query()->latest()->paginate(15);

// Cursor pagination is also supported
return User::query()->latest()->cursorPaginate(10);
```

### Paginated response schema

[](#paginated-response-schema)

```
{
  "success": true,
  "message": "Success",
  "data": [
    { "id": 1, "name": "Alice" },
    { "id": 2, "name": "Bob" }
  ],
  "meta": {
    "request_id": "LH-XXXXXX",
    "timestamp": "2026-01-27T12:00:00Z",
    "pagination": {
      "current_page": 1,
      "last_page": 5,
      "per_page": 10,
      "total": 50,
      "from": 1,
      "to": 10,
      "next_page_url": "https://example.com/api/users?page=2",
      "prev_page_url": null
    }
  }
}
```

### Manual usage (Facade)

[](#manual-usage-facade)

```
use LaraHub\ApiResponseKit\Facades\ApiResponseKit;

return ApiResponseKit::paginated(
    User::query()->latest()->paginate(15),
    'Users fetched successfully'
);
```

### Using the config per\_page helper

[](#using-the-config-per_page-helper)

Keep your per-page number in one place — `config/api-response-kit.php`:

```
// Returns the value of pagination.per_page (default: 10)
return ApiResponseKit::paginated(
    User::query()->latest()->paginate(ApiResponseKit::perPage())
);
```

### Configuration

[](#configuration)

Publish the config and adjust the default:

```
// config/api-response-kit.php
'pagination' => [
    'per_page' => env('API_RESPONSE_KIT_PER_PAGE', 10),
],
```

Or set it in `.env`:

```
API_RESPONSE_KIT_PER_PAGE=15
```

---

Manual Usage (Facade)
---------------------

[](#manual-usage-facade-1)

```
use LaraHub\ApiResponseKit\Facades\ApiResponseKit;

// Success responses
ApiResponseKit::success($data, 'User fetched');          // 200
ApiResponseKit::created($data, 'Resource created');      // 201
ApiResponseKit::accepted($data, 'Request accepted');     // 202
ApiResponseKit::noContent();                             // 204

// Error responses
ApiResponseKit::badRequest('Invalid input', $errors);    // 400
ApiResponseKit::unauthorized('Please log in');           // 401
ApiResponseKit::forbidden('Access denied');              // 403
ApiResponseKit::notFound('Resource not found');          // 404
ApiResponseKit::methodNotAllowed();                      // 405
ApiResponseKit::conflict('Duplicate entry', $errors);   // 409
ApiResponseKit::unprocessableEntity('Failed', $errors); // 422
ApiResponseKit::tooManyRequests();                       // 429
ApiResponseKit::serverError('Oops', $errors);           // 500
ApiResponseKit::serviceUnavailable();                   // 503

// Validation errors
ApiResponseKit::validationError($errors, 'Validation failed');

// Exceptions
ApiResponseKit::exception($throwable);

// Request ID
$id = ApiResponseKit::getRequestId();
ApiResponseKit::setRequestId('my-trace-id');
```

---

Middleware
----------

[](#middleware)

The package registers a middleware alias:

- `api-response-kit`

Auto-registration is controlled by config keys:

- `api-response-kit.auto_middleware`
- `api-response-kit.middleware.enabled`
- `api-response-kit.middleware.global`
- `api-response-kit.middleware.exclude`

---

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

[](#configuration-1)

### Customizing Schema Keys and Defaults

[](#customizing-schema-keys-and-defaults)

Edit `config/api-response-kit.php`:

- `keys.*` — override key names (`success`, `message`, `data`, `errors`, `meta`)
- `default_message` — default success message
- `request_id_prefix` — prefix for generated request IDs

### Debug Mode

[](#debug-mode)

```
return [
    'debug' => [
        'show_trace' => env('APP_DEBUG', false),
        'hide_sql_errors' => env('APP_ENV') === 'production',
    ],
];
```

In `APP_DEBUG=true` (development): full error details and stack traces are included.
In production: SQL queries, stack traces, and file paths are hidden.

### Custom Formatters

[](#custom-formatters)

You can provide your own formatter classes via config:

```
return [
    'formatter' => null,
    'custom_formatters' => [
        // 'my_custom_format' => App\Formatters\MyCustomFormatter::class,
    ],
];
```

Config keys:

- `api-response-kit.formatter` — default formatter implementation
- `api-response-kit.custom_formatters` — named formatters
- `api-response-kit.formatters.*` — override built-in per type: `success` / `error` / `validation` / `exception`

For safety/backwards-compatibility, per-type overrides should extend the built-in formatter they replace.

---

Package Architecture
--------------------

[](#package-architecture)

### Folder Structure

[](#folder-structure)

```
api-response-kit/
├── config/
│   └── api-response-kit.php
├── src/
│   ├── ApiResponseKitServiceProvider.php
│   ├── ApiResponseKit.php
│   ├── Facades/
│   │   └── ApiResponseKit.php
│   ├── Middleware/
│   │   └── ApiResponseKitMiddleware.php
│   ├── Formatters/
│   │   ├── SuccessFormatter.php
│   │   ├── ErrorFormatter.php
│   │   ├── ValidationFormatter.php
│   │   └── ExceptionFormatter.php
│   ├── Contracts/
│   │   └── ResponseFormatterInterface.php
│   └── Support/
│       ├── ResponseSchema.php
│       ├── RequestIdGenerator.php
│       └── ConfigResolver.php
├── tests/
│   ├── TestCase.php
│   ├── SuccessFormatterTest.php
│   ├── ErrorFormatterTest.php
│   └── MiddlewareTest.php
├── phpunit.xml
├── composer.json
└── README.md

```

### Core Components

[](#core-components)

ComponentResponsibility`ApiResponseKitServiceProvider`Register services, publish config, bind into Laravel container`ApiResponseKitMiddleware`Intercept responses, detect type, apply appropriate formatter`SuccessFormatter`Format successful responses`ErrorFormatter`Format generic errors and HTTP exceptions`ValidationFormatter`Format validation error responses`ExceptionFormatter`Convert exceptions into standardized JSON errors`ResponseSchema`Build final response structure based on config`RequestIdGenerator`Generate unique request IDs`ConfigResolver`Resolve configuration values dynamically`ApiResponseKit` (Facade)Manual response control when automatic formatting is not desired---

Testing
-------

[](#testing)

The package ships with a PHPUnit test suite powered by **[Orchestra Testbench](https://github.com/orchestral/testbench)**, which boots a real Laravel application for each test.

### Requirements

[](#requirements)

DependencyVersion`phpunit/phpunit``^10.0 | ^11.0``orchestra/testbench``^8.0 | ^9.0 | ^10.0`Install dev dependencies (first time only):

```
composer install
```

### Run the Test Suite

[](#run-the-test-suite)

```
./vendor/bin/phpunit
```

Or via the `composer test` script if you add one:

```
# composer.json → scripts
"test": "vendor/bin/phpunit"
```

```
composer test
```

### Test Structure

[](#test-structure)

FileWhat it covers`tests/TestCase.php`Base class — boots the service provider, registers the facade, enables debug mode`tests/SuccessFormatterTest.php``SuccessFormatter`, `ApiResponseKit::success/created/accepted/noContent/paginated`, request ID helpers, data normalisation`tests/ErrorFormatterTest.php``ErrorFormatter`, `ValidationFormatter`, `ExceptionFormatter`, all `ApiResponseKit` error/HTTP-status helpers`tests/MiddlewareTest.php``ApiResponseKitMiddleware` — pass-through conditions, success wrapping, pagination detection, error/validation formatting, exception catching### Test Environment

[](#test-environment)

The base `TestCase` pre-configures the following for every test:

```
$app['config']->set('app.env', 'testing');
$app['config']->set('app.debug', true);
$app['config']->set('api-response-kit.debug.show_trace', true);
$app['config']->set('api-response-kit.debug.hide_sql_errors', false);
```

Each test method receives a **fresh application instance**, so config overrides in one test cannot bleed into another.

### Example: Override Config Per Test

[](#example-override-config-per-test)

```
public function test_exception_hides_details_in_production(): void
{
    $this->app['config']->set('api-response-kit.debug.show_trace', false);

    $data = $this->kit->exception(new \RuntimeException('secret'))->getData(true);

    $this->assertSame('An unexpected error occurred', $data['message']);
    $this->assertNull($data['errors']);
}
```

---

Target Users
------------

[](#target-users)

- Laravel backend developers
- API-driven applications (REST APIs)
- Development teams requiring standardized API contracts
- SaaS and enterprise Laravel projects

---

Roadmap
-------

[](#roadmap)

### v2 (Planned)

[](#v2-planned)

- API versioning support
- Multiple response schemas
- Advanced logging integration

### v3 (Planned)

[](#v3-planned)

- API documentation auto-generation
- Frontend SDK integration
- Enterprise-level customization

###  Health Score

35

—

LowBetter than 80% of packages

Maintenance81

Actively maintained with recent releases

Popularity2

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity44

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 90% 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

2

Last Release

111d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/99dbfee297169b7418cff911dc28b5ed934292926149f94a9fafaabfcf27e27c?d=identicon)[Libin K K](/maintainers/Libin%20K%20K)

---

Top Contributors

[![libin-k-k](https://avatars.githubusercontent.com/u/96257125?v=4)](https://github.com/libin-k-k "libin-k-k (9 commits)")[![libinLilac](https://avatars.githubusercontent.com/u/196610830?v=4)](https://github.com/libinLilac "libinLilac (1 commits)")

---

Tags

responsejsonapilaravelvalidationresterror handlingstandardizationlarahub

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/larahub-api-response-kit/health.svg)

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

###  Alternatives

[guanguans/laravel-api-response

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

485.6k](/packages/guanguans-laravel-api-response)

PHPackages © 2026

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