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

ActiveLibrary[API Development](/categories/api)

sgflores/api-response-formatter
===============================

A Laravel package that automatically formats API responses to a consistent structure

v1.0.1(2mo ago)07MITPHPPHP ^8.1

Since Dec 15Pushed 2mo agoCompare

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

READMEChangelog (2)Dependencies (6)Versions (4)Used By (0)

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

[](#api-response-formatter)

A Laravel package that automatically formats API responses to a consistent structure.

Features
--------

[](#features)

- Automatically formats JSON responses for API routes
- Handles success and error responses consistently
- Supports validation error formatting
- Configurable API route patterns
- Easy to integrate with existing Laravel applications

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

[](#installation)

Install the package via Composer:

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

Publish the configuration file (optional):

```
php artisan vendor:publish --provider="SgFlores\ApiResponseFormatter\ApiResponseFormatterServiceProvider" --tag="config"
```

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

[](#configuration)

The package comes with a simple configuration file that allows you to customize its behavior:

```
// config/api-response-formatter.php

return [
    // API route pattern to match
    'api_pattern' => env('API_RESPONSE_FORMATTER_PATTERN', 'api/*'),

    // HTTP status codes considered successful
    'success_codes' => [200, 201, 202, 204],
];
```

Usage
-----

[](#usage)

### Method 1: Global Middleware (Recommended)

[](#method-1-global-middleware-recommended)

Add the middleware to your `app/Http/Kernel.php`:

```
protected $middleware = [
    // ... other middleware
    \SgFlores\ApiResponseFormatter\Http\Middleware\FormatResponse::class,
];
```

### Method 2: Route Middleware

[](#method-2-route-middleware)

Apply the middleware to specific routes:

```
Route::middleware(['api.format'])->group(function () {
    Route::get('/api/users', [UserController::class, 'index']);
    Route::post('/api/users', [UserController::class, 'store']);
});
```

### Method 3: Controller Middleware

[](#method-3-controller-middleware)

Apply the middleware to specific controllers:

```
class UserController extends Controller
{
    public function __construct()
    {
        $this->middleware('api.format');
    }
}
```

Response Format
---------------

[](#response-format)

The middleware automatically formats responses to this structure:

### Success Response

[](#success-response)

```
{
    "success": true,
    "message": "Optional success message",
    "data": {
        "id": 1,
        "name": "John Doe",
        "email": "john@example.com"
    }
}
```

### Error Response

[](#error-response)

```
{
    "success": false,
    "message": "Error message",
    "data": null,
    "errors": {
        "field": ["Validation error message"]
    }
}
```

### Paginated Response

[](#paginated-response)

```
{
    "success": true,
    "message": "Data retrieved successfully",
    "data": [
        {"id": 1, "name": "Item 1"},
        {"id": 2, "name": "Item 2"}
    ],
    "pagination": {
        "current_page": 1,
        "per_page": 10,
        "total": 25,
        "last_page": 3
    }
}
```

Examples
--------

[](#examples)

### Before Formatting

[](#before-formatting)

```
// Controller returns
return response()->json(['name' => 'John', 'email' => 'john@example.com']);

// Results in
{
    "name": "John",
    "email": "john@example.com"
}
```

### After Formatting

[](#after-formatting)

```
{
    "success": true,
    "message": null,
    "data": {
        "name": "John",
        "email": "john@example.com"
    }
}
```

Testing
-------

[](#testing)

Run the test suite:

```
composer test
```

License
-------

[](#license)

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

Contributing
------------

[](#contributing)

1. Fork the repository
2. Create your feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add some amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request

###  Health Score

37

—

LowBetter than 83% of packages

Maintenance87

Actively maintained with recent releases

Popularity4

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

Total

2

Last Release

65d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/8dc8d8a8aecd7a8cc14e17ac33fc642f394acfd2d8af482a6e27e76a6becabd6?d=identicon)[sgflores](/maintainers/sgflores)

---

Top Contributors

[![sgflores](https://avatars.githubusercontent.com/u/8511559?v=4)](https://github.com/sgflores "sgflores (8 commits)")

---

Tags

responseformattermiddlewareapilaravel

###  Code Quality

TestsPHPUnit

### Embed Badge

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

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

###  Alternatives

[obiefy/api-response

Simple Laravel package to return Json responses.

17324.6k](/packages/obiefy-api-response)[imliam/laravel-throttle-simultaneous-requests

Throttle the current user's requests based on how many requests are currently being executed.

4623.0k](/packages/imliam-laravel-throttle-simultaneous-requests)[dragon-code/laravel-json-response

Automatically always return a response in JSON format

1118.6k1](/packages/dragon-code-laravel-json-response)[vinelab/api-manager

Laravel API Manager Package - beatify and unify your responses with the least effort possible.

392.1k](/packages/vinelab-api-manager)

PHPackages © 2026

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