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.
- 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
- PHP 8.1 or higher (required for PHP enums)
- Laravel 10.43.0 or higher
This package has been optimized to use the minimal set of Laravel components:
- illuminate/config
- illuminate/contracts
- illuminate/http
- illuminate/pagination
- illuminate/support
- illuminate/validation
- symfony/http-foundation
- psr/log
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.
composer require i3rror/lapi-response
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
Run the following command to publish the package configuration:
php artisan vendor:publish --provider="MA\LaravelApiResponse\Providers\APIResponseProvider" --tag="lapi-response-config"
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
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.
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"
}
return $this->apiOk("Operation completed successfully", "Message");
Response:
{
"status": true,
"statusCode": 200,
"timestamp": 1662104853,
"message": "Message",
"data": "Operation completed successfully"
}
return $this->apiOk($yourDataArray, "Message");
Response:
{
"status": true,
"statusCode": 200,
"timestamp": 1662105038,
"message": "Message",
"data": [
{
"id": 1,
"name": "Example"
}
]
}
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;
}
}
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"]
}
return $this->apiBadRequest("Invalid parameters");
return $this->apiResponse([
'type' => 'notfound',
'message' => 'Resource not found',
'errorCode' => 'RESOURCE_NOT_FOUND',
]);
created
- 201 Createdaccepted
- 202 Acceptednotfound
- 404 Not Foundconflict
- 409 Conflictbadrequest
- 400 Bad Requestexception
- 422 Unprocessable Entityunauthenticated
- 401 Unauthorizedunauthorized
- 401 Unauthorizedforbidden
- 403 Forbiddenok
- 200 OK
$data = $this->apiValidate($request, [
'email' => ['required', 'email'],
'password' => ['required', 'min:8']
]);
If validation fails, it returns a standardized error response with validation errors.
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.',
}
$users = User::paginate(10);
return $this->apiPaginate($users);
The response includes pagination metadata with page information and navigation links.
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.
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)
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'
]
]);
{
"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"
}
// As trait methods
$this->apiOk($data = null)
$this->apiResponse($data = null)
// As helper functions
apiOk($data = null)
apiResponse($data = null)
// 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 = [])
// 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 = [])
// 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 = [])
The package provides extensive configuration options in config/response.php
:
// Remove null values from arrays
'removeNullDataValues' => false,
// Set empty data to null
'setNullEmptyData' => true,
// Format of validation errors
'returnValidationErrorsKeys' => true,
// 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,
php artisan lapi-response:publish-error-codes
With custom class name:
php artisan lapi-response:publish-error-codes CustomErrorCodesEnum
This package includes a comprehensive test suite. To run the tests:
composer install
vendor/bin/phpunit
The test suite covers:
- Basic API responses (success, error, etc.)
- Pagination functionality
- Validation handling
- Error code handling
- Exception handling
- Helper functions
The MIT License (MIT). Please see License File for more information.