PHPackages                             v-sajidnawaz-t/laravel-api-responder - 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. v-sajidnawaz-t/laravel-api-responder

ActiveLibrary[API Development](/categories/api)

v-sajidnawaz-t/laravel-api-responder
====================================

A Laravel package for standardized API responses.

v1.0.2(4mo ago)02MITPHPPHP ^8.1

Since Feb 9Pushed 4mo agoCompare

[ Source](https://github.com/sajidthedev/laravel-api-responder)[ Packagist](https://packagist.org/packages/v-sajidnawaz-t/laravel-api-responder)[ RSS](/packages/v-sajidnawaz-t-laravel-api-responder/feed)WikiDiscussions main Synced today

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

Laravel API Responder
=====================

[](#laravel-api-responder)

[![Packagist Version](https://camo.githubusercontent.com/ce1ef443699a90e9e5d33ecb5032ddb18eb38905df530f8264b8ef70b9b8294b/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f73616a69647468656465762f6c61726176656c2d6170692d726573706f6e646572)](https://camo.githubusercontent.com/ce1ef443699a90e9e5d33ecb5032ddb18eb38905df530f8264b8ef70b9b8294b/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f73616a69647468656465762f6c61726176656c2d6170692d726573706f6e646572)[![Downloads](https://camo.githubusercontent.com/bc619b2b54b969b15ccd216749917f52cd53b7dda79a42b65bcaeb4246c29184/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f73616a69647468656465762f6c61726176656c2d6170692d726573706f6e646572)](https://camo.githubusercontent.com/bc619b2b54b969b15ccd216749917f52cd53b7dda79a42b65bcaeb4246c29184/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f73616a69647468656465762f6c61726176656c2d6170692d726573706f6e646572)[![Laravel](https://camo.githubusercontent.com/93554d1ac44e7880097a6bd117e99f90c33ddf03dcf0a37f3047fa50b8aaa4d2/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c61726176656c2d31302532422d726564)](https://camo.githubusercontent.com/93554d1ac44e7880097a6bd117e99f90c33ddf03dcf0a37f3047fa50b8aaa4d2/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c61726176656c2d31302532422d726564)[![License](https://camo.githubusercontent.com/127640ddf6e5c63ce787f2463c6aa1160bf1cfbec4ee2b219e178455ca6acafc/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f73616a69647468656465762f6c61726176656c2d6170692d726573706f6e646572)](https://camo.githubusercontent.com/127640ddf6e5c63ce787f2463c6aa1160bf1cfbec4ee2b219e178455ca6acafc/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f73616a69647468656465762f6c61726176656c2d6170692d726573706f6e646572)

A lightweight, opinionated Laravel package that provides **standardized API responses**, **DTO-driven data flow**, **unified error handling**, and **optional API versioning**.

Designed for clean APIs, large teams, and scalable backend systems.

---

Features
--------

[](#features)

- ✅ **Consistent JSON Contract**: Guaranteed response structure.
- ✅ **DTO Support**: Clean data boundaries and type safety.
- ✅ **Unified Error Handling**: Standardized error codes and details.
- ✅ **Pagination Support**: Automatic meta extraction from Laravel paginators.
- ✅ **Optional Versioning**: Header-based version resolving.
- ✅ **Developer Friendly**: Non-intrusive and PSR-compliant.

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

[](#requirements)

- **PHP**: ^8.1
- **Laravel**: ^10.0 | ^11.0 | ^12.0

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

[](#installation)

```
composer require v-sajidnawaz-t/laravel-api-responder
```

*No manual service provider registration is required (Laravel auto-discovery).*

### Configuration (Optional)

[](#configuration-optional)

To publish the configuration file for versioning settings:

```
php artisan vendor:publish --provider="ApiResponder\Providers\ApiResponderServiceProvider" --tag="config"
```

---

Response Contract
-----------------

[](#response-contract)

### Success Response

[](#success-response)

```
{
  "success": true,
  "data": { "id": 1, "name": "John Doe" },
  "meta": { "version": "1.0" },
  "error": null
}
```

### Error Response

[](#error-response)

```
{
  "success": false,
  "data": null,
  "meta": {},
  "error": {
    "code": "USER_NOT_FOUND",
    "message": "The user does not exist",
    "details": []
  }
}
```

---

Usage Guide
-----------

[](#usage-guide)

### 1. Standard API Responses

[](#1-standard-api-responses)

Use the `ApiResponse` class for consistent JSON output.

```
use ApiResponder\Http\Responses\ApiResponse;

// Simple success
return ApiResponse::success(['id' => 1, 'name' => 'John']);

// Success with meta information
return ApiResponse::success($data, ['version' => '1.0']);

// Standardized error
return ApiResponse::error(
    code: 'USER_NOT_FOUND',
    message: 'User does not exist',
    details: [],
    status: 404
);

// Error from registered code
return ApiResponse::errorFromCode('USER_NOT_FOUND', details: ['id' => 1]);
```

### 2. Data Transfer Objects (DTO)

[](#2-data-transfer-objects-dto)

Extend `BaseDTO` for type-safe data handling.

```
use ApiResponder\DTO\BaseDTO;
use Illuminate\Database\Eloquent\Model;

class UserDTO extends BaseDTO
{
    public function __construct(
        public readonly int $id,
        public readonly string $email,
        public readonly string $name
    ) {}

    public static function fromModel(Model $model): static
    {
        return new static($model->id, $model->email, $model->name);
    }

    public static function fromArray(array $data): static
    {
        return new static($data['id'], $data['email'], $data['name']);
    }

    public function toArray(): array
    {
        return [
            'id' => $this->id,
            'email' => $this->email,
            'name' => $this->name,
        ];
    }
}
```

### 3. Pagination Support

[](#3-pagination-support)

Standardize paginated collections effortlessly.

```
$paginator = User::paginate(15);

return ApiResponse::paginated(
    $paginator,
    fn($user) => UserDTO::fromModel($user)->toArray()
);
```

### 4. Global Error Handling

[](#4-global-error-handling)

Integrate the `HandlesApiExceptions` trait into your `app/Exceptions/Handler.php`.

```
use ApiResponder\Exceptions\HandlesApiExceptions;

class Handler extends ExceptionHandler
{
    use HandlesApiExceptions;

    public function render($request, Throwable $e)
    {
        if ($request->is('api/*')) {
            return $this->handleApiExceptions($e) ?: parent::render($request, $e);
        }

        return parent::render($request, $e);
    }
}
```

API Versioning (Optional)
-------------------------

[](#api-versioning-optional)

Configure supported versions in `config/api_responder.php`.

> **Note:** DTOs are intentionally not versioned. Versioning is applied only at the response layer to avoid duplication and data drift.

Clients specify the version via headers:

- `X-API-Version: v2`
- `Accept-Version: v2`

---

Error Code Registry (Optional)
------------------------------

[](#error-code-registry-optional)

Centralize error definitions in `config/api_responder.php`.

```
'error_codes' => [
    'USER_NOT_FOUND' => [
        'message' => 'The requested user does not exist.',
        'status' => 404
    ],
],
```

Usage in controllers:

```
return ApiResponse::errorFromCode('USER_NOT_FOUND');
```

Deprecation Headers (Optional)
------------------------------

[](#deprecation-headers-optional)

Automatically inject RFC-compliant deprecation headers.

### 1. Configuration

[](#1-configuration)

Define deprecations by route name or path pattern in `config/api_responder.php`.

```
'deprecations' => [
    'users.show' => [
        'sunset' => '2026-12-31T00:00:00Z',
        'link' => 'https://api.example.com/docs/v2',
        'message' => 'Endpoint replaced by v2/users/{id}'
    ],
    'api/v1/*' => [
        'sunset' => '2027-01-01T00:00:00Z'
    ],
],
```

### 2. Middleware Registration

[](#2-middleware-registration)

Apply the middleware to your API routes:

```
Route::middleware(\ApiResponder\Deprecation\Middleware\ApiDeprecationHeaders::class)->group(function () {
    Route::get('/users/{id}', [UserController::class, 'show'])->name('users.show');
});
```

The middleware injects the following headers when a match is found:

- `Deprecation: true`
- `Sunset`: The sunset timestamp (RFC1123).
- `Link`: Link to documentation with `rel="deprecation"`.
- `X-API-Deprecation-Message`: Custom migration instructions.

---

Testing
-------

[](#testing)

```
composer test
```

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

34

—

LowBetter than 75% of packages

Maintenance74

Regular maintenance activity

Popularity2

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity45

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 ~0 days

Total

3

Last Release

145d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/116505695?v=4)[sajidthedev](/maintainers/sajidthedev)[@sajidthedev](https://github.com/sajidthedev)

---

Top Contributors

[![sajidthedev](https://avatars.githubusercontent.com/u/116505695?v=4)](https://github.com/sajidthedev "sajidthedev (3 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/v-sajidnawaz-t-laravel-api-responder/health.svg)

```
[![Health](https://phpackages.com/badges/v-sajidnawaz-t-laravel-api-responder/health.svg)](https://phpackages.com/packages/v-sajidnawaz-t-laravel-api-responder)
```

###  Alternatives

[defstudio/telegraph

A laravel facade to interact with Telegram Bots

816333.9k3](/packages/defstudio-telegraph)[simplestats-io/laravel-client

Server-side analytics for Laravel that follows the full funnel from visit to registration to payment, attributed to the channel that drove it. Revenue, MRR, churn and ad-spend profit (ROAS/CAC) per channel. GDPR compliant, ad-blocker proof.

5022.0k](/packages/simplestats-io-laravel-client)[rapidez/core

Rapidez Core

1823.5k72](/packages/rapidez-core)

PHPackages © 2026

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