renslabs / laravel-api-response-formatter
a simple package Format API responses throughout your Laravel application
Package info
github.com/renslabs/laravel-api-response-formatter
pkg:composer/renslabs/laravel-api-response-formatter
Requires
- php: ^8.1|^8.2|^8.3
- illuminate/support: ^8.0|^9.0|^10.0|^11.0|^12.0|^13.0
Requires (Dev)
- open-telemetry/api: ^1.0
- orchestra/testbench: ^7.0|^8.0|^9.0|^10.0|^11.0
- phpunit/phpunit: ^7.0|^8.0|^9.0|^9.5|^10.0|^11.0|^12.0
Suggests
- open-telemetry/api: Read active OpenTelemetry trace IDs when response tracing is enabled.
Provides
None
Conflicts
None
Replaces
None
README
Laravel API Response Formatter
Laravel API Response Formatter is a class that provides methods for formatting API responses in a standardized format. It simplifies the process of creating consistent and well-structured JSON responses in your API.
Requirements
- PHP
^8.1 | ^8.2 | ^8.3 - Laravel 8, 9, 10, 11 ,12 or 13
Installation
You can install the package via composer:
composer require renslabs/laravel-api-response-formatter
The package will automatically register itself.
Function List
The Laravel API Response Formatter class provides the following functions:
| Function | Description |
|---|---|
success() |
Formats a success response with optional data, message, status, and HTTP code. |
created() |
Formats a created response with optional data, message, status, and HTTP code. |
noContent() |
Returns an empty HTTP 204 response; custom HTTP codes still use the JSON format. |
error() |
Formats an error response with optional data, message, status, and HTTP code. |
unAuthenticated() |
Formats an unauthenticated response with optional data, message, status, and HTTP code. |
forbidden() |
Formats a forbidden response with optional data, message, status, and HTTP code. |
notFound() |
Formats a not found response with optional data, message, status, and HTTP code. |
methodNotAllowed() |
Formats a method not allowed response with optional data, message, status, and HTTP code. |
failedValidation() |
Formats a failed validation response with optional data, message, status, and HTTP code. |
Parameters
The functions in the Laravel API Response Formatter class accept the following parameters:
$data(optional): The data to be included in the response. It can be of any type.$message(optional): The message to be included in the response. If not provided, a default message will be used.$status(optional): The success status of the response. Defaults totruefor success responses andfalsefor error responses.$httpCode(optional): The HTTP response code to be returned. It defaults to the corresponding HTTP status code for each response type.
Example Usage
Here's an example of how you can use the Laravel API Response Formatter class in a user controller:
<?php use renslabs\ApiResponseFormatter\ApiResponse; class UserController extends Controller { public function show($id): JsonResponse { $user = User::find($id); if ($user) { return ApiResponse::success($user); } else { return ApiResponse::notFound(null, 'User not found'); } } public function create(Request $request): JsonResponse { // Validation logic if ($validationFails) { return ApiResponse::failedValidation($validationErrors); } $user = User::create($request->all()); return ApiResponse::created($user); } }
In the above example, the show() method fetches a user by ID and returns a success response if the user exists. If the user is not found, it returns a not found response. The create() method performs validation and creates a new user. If the validation fails, it returns a failed validation response. Otherwise, it returns a created response with the created user.
{
"meta": {
"code": 200,
"success": true,
"message": "OK"
},
"result": {
"id": 1,
"name": "John Doe",
"email": "john@example.com"
}
}
And for an error case:
{
"meta": {
"code": 404,
"success": false,
"message": "User not found"
},
"result": null
}
The meta object contains information about the response, such as the response code, status, and message. The result object holds the actual response data.
Note: The examples provided are simplified and may require modifications to fit your specific use case
Optional OpenTelemetry trace IDs
Response tracing is disabled by default. Enable it in your application's .env:
API_RESPONSE_TRACE_ENABLED=true
You can optionally publish the configuration:
php artisan vendor:publish --tag=api-response-formatter-config
The setting is api-response-formatter.trace.enabled. Rebuild your application's config cache after changing the setting if you use php artisan config:cache.
When enabled and a valid OpenTelemetry span context is active, all formatter methods return the current trace ID in meta.trace_id and the X-Trace-Id response header:
{
"meta": {
"code": 200,
"success": true,
"message": "OK",
"trace_id": "4bf92f3577b34da6a3ce929d0e0e4736"
},
"result": { "id": 1 }
}
If OpenTelemetry is not installed, no span context is valid, or the feature is disabled, both the field and header are omitted. The package does not generate IDs or read client headers directly. It reads the active context each time a response is created and does not retain IDs between requests.
HTTP 204 responses have an empty body, including when tracing is disabled. A valid trace ID is available through the header only. Existing method signatures and custom HTTP status codes remain supported. For browser clients on another origin, expose X-Trace-Id in your application's CORS configuration if the frontend needs to read the header.
The package does not require an OpenTelemetry SDK or extension. Those are installed by the application when it needs instrumentation and telemetry export. A valid ID can appear even for an unsampled context; sampling and export success determine whether that trace is actually available in your tracing backend.
Sending traces to SigNoz
Follow the official SigNoz PHP/Laravel instrumentation guide for your deployment. The following setup belongs in the consuming Laravel application.
Install and enable the OpenTelemetry extension in the PHP runtime serving your application, then verify it with php --ri opentelemetry. Install the application dependencies:
composer require open-telemetry/sdk open-telemetry/exporter-otlp php-http/guzzle7-adapter open-telemetry/opentelemetry-auto-laravel
Set these variables in the process environment before Composer autoload runs (for example, Docker, your service manager, or PHP-FPM configuration). Setting them only in Laravel's .env can be too late for SDK autoload initialization.
OTEL_PHP_AUTOLOAD_ENABLED=true OTEL_SERVICE_NAME=my-laravel-api OTEL_TRACES_EXPORTER=otlp OTEL_METRICS_EXPORTER=none OTEL_LOGS_EXPORTER=none OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf OTEL_EXPORTER_OTLP_ENDPOINT=https://ingest.<region>.signoz.cloud:443 OTEL_EXPORTER_OTLP_HEADERS=signoz-ingestion-key=<your-ingestion-key> OTEL_PROPAGATORS=baggage,tracecontext
For self-hosted SigNoz, replace the endpoint with your Collector's OTLP HTTP endpoint and remove the Cloud ingestion header. Ensure PHP-FPM receives the required OTEL_* variables. Restart the application workers after changing runtime configuration.
Instrumentation creates spans and handles incoming traceparent propagation. The formatter only reads the resulting context; it does not create spans, initialize exporters, or send telemetry.
Correlating Laravel logs
Read IDs from the same active context when enriching a log:
use Illuminate\Support\Facades\Log; use OpenTelemetry\API\Trace\Span; $context = Span::getCurrent()->getContext(); $logContext = ['order_id' => $order->id]; if ($context->isValid()) { $logContext['trace_id'] = $context->getTraceId(); $logContext['span_id'] = $context->getSpanId(); } Log::info('Order created', $logContext);
This example assumes the application's OpenTelemetry integration is installed. Configure an OpenTelemetry log bridge or Collector log ingestion to send these structured logs and map the IDs to the trace/span fields expected by SigNoz. Enabling response tracing does not enable log export. See SigNoz log/trace correlation.
Verification
Run package tests with composer install followed by composer test. Tests activate OpenTelemetry contexts locally and do not need a Collector, SigNoz, or the OpenTelemetry extension. An isolated process also checks behavior with the optional OpenTelemetry API unavailable.
In staging, enable response tracing and configure the application's instrumentation to sample the test requests. Call a formatter-backed endpoint, copy meta.trace_id (or X-Trace-Id for HTTP 204), and find that ID in SigNoz's Traces view after export. If it is missing, check sampling, exporter connectivity, and runtime environment variables. A valid response ID alone does not prove successful export.
Contributing
Please see CONTRIBUTING for details.
Security
If you discover any security related issues, please email okriizaa@gmail.com instead of using the issue tracker.
Credits
This package was created by RensLabs
License
The Laravel API Response Formatter package is open-sourced software licensed under the MIT license.