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.

FAQ

After the download, you have to make one include require_once('vendor/autoload.php');. After that you have to import the classes with use statements.

Example:
If you use only one package a project is not needed. But if you use more then one package, without a project it is not possible to import the classes with use statements.

In general, it is recommended to use always a project to download your libraries. In an application normally there is more than one library needed.
Some PHP packages are not free to download and because of that hosted in private repositories. In this case some credentials are needed to access such packages. Please use the auth.json textarea to insert credentials, if a package is coming from a private repository. You can look here for more information.

  • Some hosting areas are not accessible by a terminal or SSH. Then it is not possible to use Composer.
  • To use Composer is sometimes complicated. Especially for beginners.
  • Composer needs much resources. Sometimes they are not available on a simple webspace.
  • If you are using private repositories you don't need to share your credentials. You can set up everything on our site and then you provide a simple download link to your team member.
  • Simplify your Composer build process. Use our own command line tool to download the vendor folder as binary. This makes your build process faster and you don't need to expose your credentials for private repositories.
Please rate this library. Is it a good library?

Informations about the package api-response-formatter

api-response-formatter

Latest Version on Packagist PHP Version Laravel Tests

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

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 args are 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:


Contributing

Contributions are welcome! Please follow these steps:

  1. Fork the repository and create a branch from main.
  2. Write tests for any new feature or bug fix — PRs without tests will not be merged.
  3. Run the test suite and ensure everything passes: composer test
  4. Apply code style with Laravel Pint: composer lint
  5. Update CHANGELOG.md under an [Unreleased] heading.
  6. 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

PHP Build Version
Package Version
Requires php Version ^8.1
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
Composer command for our command line client (download client) This client runs in each environment. You don't need a specific PHP version etc. The first 20 API calls are free. Standard composer command

The package nilanjan-k/api-response-formatter contains the following files

Loading the files please wait ...