PHPackages                             greelogix/api-response-formatter - 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. greelogix/api-response-formatter

ActiveLibrary[API Development](/categories/api)

greelogix/api-response-formatter
================================

A Laravel package that standardizes API responses across projects with support for multiple formats (custom, jsend, json\_api) and Laravel Resources.

v1.0.0(5mo ago)01MITPHPPHP ^8.1

Since Jan 22Pushed 5mo agoCompare

[ Source](https://github.com/greelogix/api-response-formatter)[ Packagist](https://packagist.org/packages/greelogix/api-response-formatter)[ RSS](/packages/greelogix-api-response-formatter/feed)WikiDiscussions main Synced today

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

API Response Formatter
======================

[](#api-response-formatter)

A Laravel package that standardizes API responses across projects with support for multiple formats (custom, jsend, json\_api) and Laravel Resources.

Features
--------

[](#features)

- ✅ **Simple to use** - Works out-of-the-box after installation
- ✅ **Multiple formats** - Support for custom, JSend, and JSON:API formats
- ✅ **Laravel Resources** - Automatic detection and formatting of Laravel API Resources
- ✅ **Configurable** - All options configurable via config file and environment variables
- ✅ **Consistent structure** - Provides consistent response structure across your API
- ✅ **Default status codes** - Configurable default status codes with per-call overrides
- ✅ **Auto messages** - Automatic message generation based on response type
- ✅ **Pagination support** - Automatic pagination metadata extraction and formatting
- ✅ **Laravel 8, 9, 10, 11** - Full support for multiple Laravel versions

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

[](#installation)

Install the package via Composer:

```
composer require greelogix/api-response-formatter
```

The package will automatically register its service provider.

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

[](#configuration)

Publish the configuration file:

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

This will create `config/gl-api-response-formatter.php` with the following default configuration:

```
return [
    'format' => 'custom',  // default format
    'messages_enabled' => true,
    'auto_messages' => true,
    'message_single' => 'Data fetched successfully.',
    'message_collection' => 'Records fetched successfully.',
    'message_paginated' => 'Paginated results fetched successfully.',
    'message_error' => 'Something went wrong.',
    'pagination_enabled' => true,
    'pagination_key' => 'pagination',
    'resource_support' => true,
    'status_codes' => [
        'success' => 200,
        'created' => 201,
        'error' => 400,
        'validation' => 422,
        'not_found' => 404,
        'unauthorized' => 401,
    ],
];
```

### Environment Variables

[](#environment-variables)

All configuration values can be overridden using environment variables with the `GL_API_RESPONSE_FORMATTER_*` prefix:

```
GL_API_RESPONSE_FORMATTER_FORMAT=custom
GL_API_RESPONSE_FORMATTER_MESSAGES_ENABLED=true
GL_API_RESPONSE_FORMATTER_AUTO_MESSAGES=true
GL_API_RESPONSE_FORMATTER_MESSAGE_SINGLE="Data fetched successfully."
GL_API_RESPONSE_FORMATTER_MESSAGE_COLLECTION="Records fetched successfully."
GL_API_RESPONSE_FORMATTER_MESSAGE_PAGINATED="Paginated results fetched successfully."
GL_API_RESPONSE_FORMATTER_MESSAGE_ERROR="Something went wrong."
GL_API_RESPONSE_FORMATTER_PAGINATION_ENABLED=true
GL_API_RESPONSE_FORMATTER_PAGINATION_KEY=pagination
GL_API_RESPONSE_FORMATTER_RESOURCE_SUPPORT=true
GL_API_RESPONSE_FORMATTER_STATUS_SUCCESS=200
GL_API_RESPONSE_FORMATTER_STATUS_CREATED=201
GL_API_RESPONSE_FORMATTER_STATUS_ERROR=400
GL_API_RESPONSE_FORMATTER_STATUS_VALIDATION=422
GL_API_RESPONSE_FORMATTER_STATUS_NOT_FOUND=404
GL_API_RESPONSE_FORMATTER_STATUS_UNAUTHORIZED=401
```

Usage
-----

[](#usage)

### Basic Usage

[](#basic-usage)

#### Using the Static Facade

[](#using-the-static-facade)

```
use GreeLogix\ApiResponseFormatter\ApiResponse;

// Success response
return ApiResponse::success(User::all());

// With custom message
return ApiResponse::success($user, 'User retrieved successfully.');

// With custom status
return ApiResponse::success($user, status: 202);

// With meta data
return ApiResponse::success($user, meta: ['version' => '1.0']);

// Error response
return ApiResponse::error('User not found', status: 404);

// Validation error
return ApiResponse::validationError($validator->errors()->toArray());

// Not found
return ApiResponse::notFound('Resource not found');

// Unauthorized
return ApiResponse::unauthorized('Unauthorized access');

// Created response
return ApiResponse::created($newUser, 'User created successfully.');
```

#### Using the Trait in Controllers

[](#using-the-trait-in-controllers)

```
use GreeLogix\ApiResponseFormatter\ApiResponseTrait;
use Illuminate\Http\Request;

class UserController extends Controller
{
    use ApiResponseTrait;

    public function index()
    {
        $users = User::paginate(15);
        return $this->successResponse($users);
    }

    public function show($id)
    {
        $user = User::find($id);

        if (!$user) {
            return $this->errorResponse('User not found', status: 404);
        }

        return $this->successResponse($user);
    }

    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required',
            'email' => 'required|email',
        ]);

        if ($validator->fails()) {
            return $this->errorResponse(
                'Validation failed',
                $validator->errors()->toArray(),
                status: 422
            );
        }

        $user = User::create($request->all());
        return $this->successResponse($user, 'User created successfully.', status: 201);
    }
}
```

#### Using the Exception

[](#using-the-exception)

```
use GreeLogix\ApiResponseFormatter\Exceptions\ApiException;

// In your controller or service
if (!$user) {
    throw new ApiException('User not found', statusCode: 404);
}

// With validation errors
throw new ApiException(
    'Validation failed',
    statusCode: 422,
    errors: $validator->errors()->toArray()
);
```

### Laravel Resources Support

[](#laravel-resources-support)

The package automatically detects and formats Laravel API Resources:

```
use App\Http\Resources\UserResource;
use GreeLogix\ApiResponseFormatter\ApiResponse;

// Single resource
$user = User::find(1);
return ApiResponse::success(new UserResource($user));

// Resource collection
$users = User::all();
return ApiResponse::success(UserResource::collection($users));
```

### Pagination Support

[](#pagination-support)

The package automatically detects and formats paginated results:

```
use GreeLogix\ApiResponseFormatter\ApiResponse;

// Paginated response
$users = User::paginate(15);
return ApiResponse::success($users);
```

This will automatically include pagination metadata in the response.

Response Formats
----------------

[](#response-formats)

### Custom Format (Default)

[](#custom-format-default)

**Success Response:**

```
{
    "success": true,
    "message": "Data fetched successfully.",
    "data": {
        "id": 1,
        "name": "John Doe"
    }
}
```

**Collection Response:**

```
{
    "success": true,
    "message": "Records fetched successfully.",
    "data": [
        {"id": 1, "name": "John Doe"},
        {"id": 2, "name": "Jane Doe"}
    ]
}
```

**Paginated Response:**

```
{
    "success": true,
    "message": "Paginated results fetched successfully.",
    "data": [
        {"id": 1, "name": "John Doe"},
        {"id": 2, "name": "Jane Doe"}
    ],
    "pagination": {
        "current_page": 1,
        "per_page": 15,
        "total": 100,
        "last_page": 7,
        "from": 1,
        "to": 15
    }
}
```

**Error Response:**

```
{
    "success": false,
    "message": "Something went wrong.",
    "errors": {
        "email": ["The email field is required."]
    }
}
```

### JSend Format

[](#jsend-format)

To use JSend format, set `format` to `jsend` in your config:

```
'format' => 'jsend',
```

**Success Response:**

```
{
    "status": "success",
    "data": {
        "id": 1,
        "name": "John Doe"
    },
    "message": "Data fetched successfully."
}
```

**Fail Response (4xx):**

```
{
    "status": "fail",
    "message": "Validation failed",
    "data": {
        "email": ["The email field is required."]
    }
}
```

**Error Response (5xx):**

```
{
    "status": "error",
    "message": "Internal server error"
}
```

### JSON:API Format

[](#jsonapi-format)

To use JSON:API format, set `format` to `json_api` in your config:

```
'format' => 'json_api',
```

**Success Response:**

```
{
    "data": {
        "id": 1,
        "name": "John Doe"
    },
    "meta": {
        "message": "Data fetched successfully."
    }
}
```

**Error Response:**

```
{
    "errors": [
        {
            "status": "422",
            "title": "Validation Error",
            "detail": "The email field is required.",
            "source": {
                "pointer": "/data/attributes/email"
            }
        }
    ]
}
```

Status Codes
------------

[](#status-codes)

Default status codes are configured in the config file and can be overridden per response:

```
// Uses default status code from config (200)
return ApiResponse::success($data);

// Override status code
return ApiResponse::success($data, status: 202);

// Uses default created status code (201)
return ApiResponse::created($data);

// Override created status code
return ApiResponse::created($data, status: 201);
```

Messages
--------

[](#messages)

### Auto Messages

[](#auto-messages)

When `auto_messages` is enabled (default), the package automatically generates messages based on response type:

- Single item → `message_single`
- Collection → `message_collection`
- Paginated → `message_paginated`
- Error → `message_error`

### Custom Messages

[](#custom-messages)

You can provide custom messages per response:

```
return ApiResponse::success($user, 'User retrieved successfully.');
```

### Disable Messages

[](#disable-messages)

To disable messages globally:

```
'messages_enabled' => false,
```

Or disable auto messages but allow manual messages:

```
'auto_messages' => false,
```

Pagination
----------

[](#pagination)

Pagination is automatically detected and formatted. To disable pagination metadata:

```
'pagination_enabled' => false,
```

To change the pagination key:

```
'pagination_key' => 'meta', // Changes 'pagination' to 'meta'
```

Advanced Usage
--------------

[](#advanced-usage)

### Using ApiResponseManager Directly

[](#using-apiresponsemanager-directly)

```
use GreeLogix\ApiResponseFormatter\ApiResponseManager;

$manager = app(ApiResponseManager::class);
return $manager->success($data, 'Custom message', 200, ['version' => '1.0']);
```

### Custom Formatter

[](#custom-formatter)

You can create your own formatter by implementing `FormatterInterface`:

```
use GreeLogix\ApiResponseFormatter\Formatters\FormatterInterface;

class MyCustomFormatter implements FormatterInterface
{
    public function formatSuccess($data, ?string $message = null, ?array $meta = null, ?array $pagination = null): array
    {
        // Your custom format logic
    }

    public function formatError(?string $message = null, ?array $errors = null): array
    {
        // Your custom error format logic
    }
}
```

Testing
-------

[](#testing)

```
use GreeLogix\ApiResponseFormatter\ApiResponse;

// In your tests
$response = ApiResponse::success(['test' => 'data']);

$response->assertStatus(200)
    ->assertJson([
        'success' => true,
        'data' => ['test' => 'data']
    ]);
```

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

[](#requirements)

- PHP &gt;= 8.1
- Laravel &gt;= 8.0

License
-------

[](#license)

This package is open-sourced software licensed under the [MIT license](LICENSE).

Support
-------

[](#support)

For issues, questions, or contributions, please visit the [GitHub repository](https://github.com/greelogix/api-response-formatter).

Changelog
---------

[](#changelog)

Please see [CHANGELOG.md](CHANGELOG.md) for more information on what has changed recently.

###  Health Score

32

—

LowBetter than 69% of packages

Maintenance71

Regular maintenance activity

Popularity1

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity43

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

Unknown

Total

1

Last Release

162d ago

### Community

Maintainers

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

---

Top Contributors

[![Fatima-Saeed](https://avatars.githubusercontent.com/u/61150734?v=4)](https://github.com/Fatima-Saeed "Fatima-Saeed (1 commits)")

---

Tags

responseformatterapilaravelJSON-APIjsendgreelogix

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/greelogix-api-response-formatter/health.svg)

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

###  Alternatives

[psalm/plugin-laravel

Psalm plugin for Laravel

3355.3M345](/packages/psalm-plugin-laravel)[defstudio/telegraph

A laravel facade to interact with Telegram Bots

816333.6k3](/packages/defstudio-telegraph)[api-platform/laravel

API Platform support for Laravel

58171.5k14](/packages/api-platform-laravel)[essa/api-tool-kit

set of tools to build an api with laravel

53390.0k](/packages/essa-api-tool-kit)[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.

5021.9k](/packages/simplestats-io-laravel-client)

PHPackages © 2026

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