i3rror / lapi-response
API Response trait for laravel
Requires
- php: >=8.1
- illuminate/config: >=10.43.0
- illuminate/contracts: >=10.43.0
- illuminate/http: >=10.43.0
- illuminate/pagination: >=10.43.0
- illuminate/support: >=10.43.0
- illuminate/validation: >=10.43.0
- psr/log: ^3.0
- symfony/http-foundation: ^6.0 || ^7.0
Requires (Dev)
- mockery/mockery: ^1.5
- orchestra/testbench: ^8.0
- phpunit/phpunit: ^10.0
Suggests
- illuminate/auth: Required for authentication exception handling
- illuminate/container: Required for standalone usage outside of Laravel
- illuminate/routing: Required for redirect functionality
- symfony/console: Required for console commands
- symfony/http-kernel: Required for HTTP exception handling
- dev-main
- v1.3.4
- v1.3.3.3
- v1.3.3.2
- v1.3.3.1
- v1.3.3
- v1.3.2
- v1.3.1
- v1.3.0
- v1.2.0
- v1.1.4
- v1.1.3
- v1.1.2
- v1.1.1
- v1.1.0
- v1.0.2
- v1.0.1
- v1.0.0
- v0.0.1-beta
- dev-dev
- dev-feature/helpers-facade-functions
- dev-feature/return-json-response
- dev-feat/validate-request
- dev-feat/hide-pagination-links
- dev-feat/append-data-to-pagination-response
- dev-feature/stream-response
- dev-feature-error-handler-0.1
This package is auto-updated.
Last update: 2025-06-14 08:30:39 UTC
README
Overview
LAPI-response is a comprehensive Laravel package that standardizes API responses across your application. It provides consistent response formatting, error handling, validation support, and pagination, making it easier to build robust APIs.
Features
- Consistent JSON Response Format: Standardized structure for all API responses
- Multiple Response Types: Support for success, error, validation, and pagination responses
- Error Handling: Built-in error handling with customizable error codes
- Validation Support: Simplified request validation with standardized error responses
- Pagination Support: Easy pagination with meta information
- Stream Response: Support for streaming large datasets
- Configurable: Extensive configuration options to customize behavior
Requirements
- PHP 8.1 or higher (required for PHP enums)
- Laravel 10.43.0 or higher
Dependencies
This package has been optimized to use the minimal set of Laravel components:
Core Dependencies
- illuminate/config
- illuminate/contracts
- illuminate/http
- illuminate/pagination
- illuminate/support
- illuminate/validation
- symfony/http-foundation
- psr/log
Optional Dependencies
The following packages are suggested for specific features:
- illuminate/auth - Required for authentication exception handling
- illuminate/container - Required for standalone usage outside of Laravel
- illuminate/routing - Required for redirect functionality
- symfony/http-kernel - Required for HTTP exception handling
- symfony/console - Required for console commands
When used within a Laravel application, these optional dependencies will be available through Laravel itself.
Installation
Step 1: Install via Composer
composer require i3rror/lapi-response
Step 2: Register Service Provider
Include the service provider in your config/app.php
or in bootstrap/providers.php
if you're using Laravel 11:
MA\LaravelApiResponse\Providers\APIResponseProvider::class
Step 3: Publish Configuration
Run the following command to publish the package configuration:
php artisan vendor:publish --provider="MA\LaravelApiResponse\Providers\APIResponseProvider" --tag="lapi-response-config"
Basic Implementation
To use this package, add the APIResponseTrait
to your controllers:
use MA\LaravelApiResponse\Traits\APIResponseTrait; class YourController extends Controller { use APIResponseTrait; // Your controller methods... }
You have two implementation options:
- Global Implementation: Add the trait to
App\Http\Controllers\Controller.php
to make it available across all controllers - Local Implementation: Add the trait only to specific controllers where API responses are needed
Helper Functions
Alternatively, you can use the package's global helper functions without adding the trait to your controllers. These functions can be used anywhere in your application:
// In any file in your application return apiOk($data, $message); return apiNotFound(["Resource not found"], "Resource not found"); return apiResponse(['message' => 'Success', 'data' => $data]);
These helper functions can be used as public functions or as internal helper functions within your application's codebase.
Usage Examples
Basic Response
return $this->apiResponse([ 'message' => 'Success Message', 'data' => $yourData, 'extra' => [ 'field1' => 'Value 1', 'field2' => 'Value 2' ], ]);
Response:
{ "status": true, "statusCode": 200, "timestamp": 1662070087, "message": "Success Message", "data": { "key": "value" }, "field1": "Value 1", "field2": "Value 2" }
Message Example:
return $this->apiOk("Operation completed successfully", "Message");
Response:
{ "status": true, "statusCode": 200, "timestamp": 1662104853, "message": "Message", "data": "Operation completed successfully" }
Data Example:
return $this->apiOk($yourDataArray, "Message");
Response:
{ "status": true, "statusCode": 200, "timestamp": 1662105038, "message": "Message", "data": [ { "id": 1, "name": "Example" } ] }
Stream Response
The stream response feature allows you to handle large datasets efficiently:
return $this->apiStreamResponse($this->yieldData(), "Streaming data", 200); protected function yieldData(): Generator { foreach (User::cursor() as $user) { yield $user; } }
Error Handling
Not Found Example
return $this->apiNotFound("Resource not found", "Error Not Found Message");
Response:
{ "status": false, "statusCode": 404, "timestamp": 1662121027, "message": "Not found!", "data": null, "errors": ["Resource not found"] }
Bad Request Example
return $this->apiBadRequest("Invalid parameters");
With Error Code
return $this->apiResponse([ 'type' => 'notfound', 'message' => 'Resource not found', 'errorCode' => 'RESOURCE_NOT_FOUND', ]);
Available Status Types
created
- 201 Createdaccepted
- 202 Acceptednotfound
- 404 Not Foundconflict
- 409 Conflictbadrequest
- 400 Bad Requestexception
- 422 Unprocessable Entityunauthenticated
- 401 Unauthorizedunauthorized
- 401 Unauthorizedforbidden
- 403 Forbiddenok
- 200 OK
Validation Support
$data = $this->apiValidate($request, [ 'email' => ['required', 'email'], 'password' => ['required', 'min:8'] ]);
If validation fails, it returns a standardized error response with validation errors.
Also we have a trait ready to use in case you're using FormRequests.
use MA\LaravelApiResponse\Traits\APIRequestValidator; class UpdateAccountRequest extends FormRequest { use APIRequestValidator; // If you want to set a custom message in the return response upon failing // You can use this protected ?string $errorMessage = 'Validation failed.', }
Pagination Support
$users = User::paginate(10); return $this->apiPaginate($users);
The response includes pagination metadata with page information and navigation links.
Available Methods
All methods listed below are available both as trait methods and as global helper functions. You can use them either way depending on your implementation preference.
Create Response
Simplified Usage for apiResponse function
You can use short parameter values in two ways:
- String parameters are set as messages
- Array parameters are set as data
// As trait methods $this->apiResponse($data = null) // As helper functions apiResponse($data = null)
Example
return $this->apiResponse([ 'status_code' => Response::HTTP_OK, 'message' => 'This is custom message', 'data' => [ 'data1' => 'custom data 1', 'data2' => 'custom data 2' ], 'extra' => [ 'extra1' => 'extra data 1', 'extra2' => 'extra data 2' ] ]);
Response
{ "status": true, "statusCode": 200, "timestamp": 1749643578, "message": "This is custom message", "data": { "data1": "custom data 1", "data2": "custom data 2" }, "extra1": "extra data 1", "extra2": "extra data 2" }
Success Responses
// As trait methods $this->apiOk($data = null) $this->apiResponse($data = null) // As helper functions apiOk($data = null) apiResponse($data = null)
Error Responses
// As trait methods $this->apiNotFound($errors = null, $throw_exception = true, $errorCode = null, $headers = []) $this->apiBadRequest($errors = null, $throw_exception = true, $errorCode = null, $headers = []) $this->apiException($errors = null, $throw_exception = true, $errorCode = null, $headers = []) $this->apiUnauthenticated($message = null, $errors = null, $errorCode = null, $headers = []) $this->apiForbidden($message = null, $errors = null, $errorCode = null, $headers = []) // As helper functions apiNotFound($errors = null, $throw_exception = true, $errorCode = null, $headers = []) apiBadRequest($errors = null, $throw_exception = true, $errorCode = null, $headers = []) apiException($errors = null, $throw_exception = true, $errorCode = null, $headers = []) apiUnauthenticated($message = null, $errors = null, $errorCode = null, $headers = []) apiForbidden($message = null, $errors = null, $errorCode = null, $headers = [])
Pagination and Validation
// As trait methods $this->apiPaginate($pagination, $appends = [], $reverse_data = false, $headers = []) $this->apiValidate($data, $rules, $messages = [], $attributes = []) // As helper functions apiPaginate($pagination, $appends = [], $reverse_data = false, $headers = []) apiValidate($data, $rules, $messages = [], $attributes = [])
Other Utilities
// As trait methods $this->apiDD($data) // Debug helper $this->apiStreamResponse($generator, $message = null, $statusCode = 200, $headers = []) // As helper functions apiDD($data) // Debug helper apiStreamResponse($generator, $message = null, $statusCode = 200, $headers = [])
Configuration
The package provides extensive configuration options in config/response.php
:
Data Handling
// Remove null values from arrays 'removeNullDataValues' => false, // Set empty data to null 'setNullEmptyData' => true, // Format of validation errors 'returnValidationErrorsKeys' => true,
Error Codes
// Enable error codes 'enableErrorCodes' => true, // Error codes enum class 'errorCodes' => \MA\LaravelApiResponse\Enums\ErrorCodesEnum::class, // Error codes output format (string or integer) 'errorCodesType' => 'string', // Return default error codes if not specified 'returnDefaultErrorCodes' => true,
Publishing Error Codes Enum
php artisan lapi-response:publish-error-codes
With custom class name:
php artisan lapi-response:publish-error-codes CustomErrorCodesEnum
Contributors
Testing
This package includes a comprehensive test suite. To run the tests:
composer install vendor/bin/phpunit
Test Coverage
The test suite covers:
- Basic API responses (success, error, etc.)
- Pagination functionality
- Validation handling
- Error code handling
- Exception handling
- Helper functions
License
The MIT License (MIT). Please see License File for more information.