Download the PHP package nilanjan-k/api-response-formatter without Composer
On this page you can find all versions of the php package nilanjan-k/api-response-formatter. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Informations about the package api-response-formatter
api-response-formatter
A production-ready Laravel package that gives every API response — success, error, validation failure, paginated list, or unhandled exception — the same predictable JSON envelope. Frontend and mobile clients always know exactly what shape to expect, regardless of which controller or service produced it.
Table of Contents
- Requirements
- Installation
- From Packagist (normal)
- Local development / path repository
- Configuration
- Publishing the config file
- Config options
- Usage
- Option A — Facade
- Option B — HasApiResponse trait
- Option C — Global helper functions
- Available methods
- Response shape reference
- Paginated responses
- Exception handler integration
- Laravel 11 and 12 (bootstrap/app.php)
- Laravel 10 (app/Exceptions/Handler.php)
- Exceptions handled automatically
- Macro support
- BaseResource
- Localization / i18n
- Security considerations
- Testing
- Contributing
- Changelog
- License
Requirements
| Dependency | Version |
|---|---|
| PHP | ^8.1 |
| Laravel | 10, 11, 12, or 13 |
Installation
From Packagist (normal)
Laravel's package auto-discovery registers the service provider and the
ApiResponse facade alias automatically. No manual edits to config/app.php
are needed.
Local development / path repository
If you are working on the package itself alongside a test application, tell
Composer where to find it via a path repository entry — no Packagist
publishing required.
1. Add the path repository to your Laravel app's composer.json:
2. Require the package:
Composer creates a symlink from vendor/nilanjan-k/api-response-formatter to
your local package folder, so every edit you make is reflected instantly — no
composer update needed.
3. Verify auto-discovery ran:
You should see NilanjanK\ApiResponseFormatter\ApiResponseServiceProvider
listed as discovered.
Configuration
Publishing the config file
The config file is published to config/api-response.php.
The lang files are published to lang/vendor/api-response/.
Config options
| Key | Type | Default | Description |
|---|---|---|---|
include_meta |
bool |
true |
Include a "meta" key in every response. null for non-paginated responses; populated for paginated responses. |
include_timestamp |
bool |
false |
Append "timestamp" (ISO-8601) to every response. |
include_request_id |
bool |
false |
Append "request_id" to every response. Uses the incoming X-Request-Id header only if it is a valid UUID v4; otherwise generates a fresh one. |
debug |
bool |
false |
When true and APP_DEBUG=true, include exception details in 500 responses. Stack-frame arguments are always stripped before serialisation. Leave false in production. |
default_messages |
array |
[] |
Override the default message for any HTTP status code. Falls back to lang/en/messages.php for missing codes. |
Usage
Three styles are available. Pick whichever fits your team's conventions — they all produce identical JSON.
Option A — Facade
Option B — HasApiResponse trait
Add use HasApiResponse directly in a controller. No static calls or
facade imports needed.
Option C — Global helper functions
Four global functions are auto-loaded via helpers.php. They are available
anywhere — middleware, jobs, service classes, Artisan commands.
Available methods
| Method | HTTP code | status |
|---|---|---|
success($data, $message, $code = 200) |
200 | true |
created($data, $message) |
201 | true |
noContent() |
204 | — |
paginated($paginator, $message, $code = 200) |
200 | true |
error($message, $code = 400, $errors) |
any | false |
validationError($errors, $message) |
422 | false |
unauthorized($message) |
401 | false |
forbidden($message) |
403 | false |
notFound($message) |
404 | false |
serverError($message, $errors) |
500 | false |
All $message and $errors parameters are optional. When $message is
omitted the package looks up a default from config/api-response.php
(default_messages) and falls back to lang/en/messages.php.
Response shape reference
Every response (except noContent) always contains the same six keys so
clients can write a single deserialiser.
Optional fields (enabled via config):
Success — 200
Created — 201
Validation error — 422
Not found — 404
Server error — 500 (with debug = true and APP_DEBUG = true)
Note: Stack-frame
argsare always removed from the trace before serialisation, even in debug mode, to prevent leaking passwords, tokens, or sensitive model state. See Security considerations.
Paginated responses
Pass any AbstractPaginator instance — including the result of
Eloquent's paginate() or simplePaginate():
Response:
simplePaginate() / CursorPaginator do not support total and
last_page — those fields will be null in the meta block.
Exception handler integration
The HandlesApiExceptions trait automatically converts unhandled exceptions
into the standard JSON envelope. Wire it up once and every unhandled exception
your application throws will return a consistent error response.
Laravel 11 and 12 (bootstrap/app.php)
Laravel 10 (app/Exceptions/Handler.php)
Exceptions handled automatically
| Exception class | Response code | Message source |
|---|---|---|
ValidationException |
422 | Exception's own errors() bag |
AuthenticationException |
401 | Exception's own message |
AuthorizationException |
403 | Generic translated message (raw message never exposed) |
ModelNotFoundException |
404 | Generic translated message |
HttpExceptionInterface |
Actual HTTP code | Exception message or lang fallback |
| Everything else | 500 | Generic translated message (+ debug block if enabled) |
Macro support
Register custom response types at runtime — for example in a
ServiceProvider::boot() method:
Then use them anywhere:
BaseResource
Extend BaseResource instead of JsonResource to have single-resource
responses automatically wrapped in the standard envelope without any extra
controller code:
In your controller:
Response:
Localization / i18n
The default English messages live in lang/en/messages.php. Publish them to
provide translations for additional locales:
Files are published to lang/vendor/api-response/. Add a sibling directory
for each locale you support — Laravel's translation system resolves the
correct file automatically based on App::getLocale().
Example lang/vendor/api-response/fr/messages.php:
You can also override a message for a specific HTTP code without touching
the lang files — use default_messages in config/api-response.php:
Security considerations
Debug mode and stack traces
Setting debug = true in config/api-response.php (together with
APP_DEBUG=true) adds exception details to 500 responses.
Stack-frame function arguments are always stripped before the trace is
serialised, even when debug mode is on. PHP's getTrace() includes the actual
runtime values passed to each function — passwords, API tokens, and model
attributes would otherwise appear verbatim in the JSON response. The package
uses array_diff_key($frame, ['args' => true]) on every frame.
Always keep debug = false in production.
X-Request-Id reflection
When include_request_id = true the incoming X-Request-Id header is
reflected in the response. The package validates the header against a strict
UUID v4 regex before echoing it. Any non-conforming value is silently replaced
with a server-generated UUID — preventing header injection and log poisoning.
AuthorizationException messages
AuthorizationException messages are never reflected in responses.
Custom policy messages often expose internal model names, record IDs, or
business-rule text (e.g. "Cannot update App\Models\BankAccount with ID 9").
The package always returns the generic translated 403 message instead.
Testing
Run the test suite inside the package directory:
The suite uses Orchestra Testbench and covers:
- Every response method returns the correct HTTP status code
- JSON envelope always contains the required six keys
status/codevalues match the HTTP code- Paginated meta block is correctly populated from the paginator
include_timestamptoggle adds / removes thetimestampkeyinclude_request_idtoggle and UUID validation / rejectioninclude_meta = falsesuppresses meta even on paginated responses- Validation error structure matches the
errorsbag - Exception handler converts
ValidationException→ 422,AuthenticationException→ 401,AuthorizationException→ 403,ModelNotFoundException→ 404,HttpException→ its code, everything else → 500 - Stack traces never contain
argseven when debug mode is on AuthorizationExceptionraw message is never reflected- Debug defaults to off when config key is missing
- Facade alias resolves to the same singleton
- Global helper functions proxy to the manager correctly
- Macros can be registered and called
Contributing
Contributions are welcome! Please follow these steps:
- Fork the repository and create a branch from
main. - Write tests for any new feature or bug fix — PRs without tests will not be merged.
- Run the test suite and ensure everything passes:
composer test - Apply code style with Laravel Pint:
composer lint - Update
CHANGELOG.mdunder an[Unreleased]heading. - Open a pull request with a clear title and description.
Please follow PSR-12 coding standards.
All new public API must include a DocBlock with @param and @return tags.
Changelog
See CHANGELOG.md for a full list of changes per release.
License
The MIT License (MIT). See LICENSE for full details.
All versions of api-response-formatter with dependencies
illuminate/support Version ^10.0|^11.0|^12.0|^13.0
illuminate/http Version ^10.0|^11.0|^12.0|^13.0
illuminate/contracts Version ^10.0|^11.0|^12.0|^13.0
illuminate/pagination Version ^10.0|^11.0|^12.0|^13.0