composer require harrisonratcliffe/laravel-api-responses
- 📍 Overview
- 👾 Features
- 🚀 Getting Started
- ☑️ Prerequisites
- ⚙ Installation
- 🤖 Usage
- 🧪 Testing
- 🔰 Contributing
- 🎗 License
A Laravel package to easily handle API responses and exceptions.
- 🌟 Return clean, consistent API responses
- 🛡️ Handle API exceptions with standardized error responses
- 🚀 Easy integration with Laravel 7 to 12
Before getting started with Laravel API Responses, ensure your runtime environment meets the following requirements:
- Programming Language: PHP
- Package Manager: Composer
- Laravel Version: 7 or later
Install laravel-api-responses using the following method:
- Install the package via Composer:
composer require harrisonratcliffe/laravel-api-responses
- Publish the config with:
php artisan vendor:publish --tag="apiresponses-config"
Note: if you use a different API route path than /api you should adjust the below if statement.
To configure the API Exception Handler on Laravel 11-12, add the following configuration to your boostrap/app.php
file:
use Harrisonratcliffe\LaravelApiResponses\ApiExceptionHandler;
->withExceptions(function (Exceptions $exceptions) {
// your other code here
$exceptions->render(function (Throwable $exception, $request) {
if ($request->expectsJson() || $request->is('api/*')) {
return app(ApiExceptionHandler::class)->renderApiException($exception);
}
});
// your other code here
})
To configure the API Exception Handler on Laravel 7-10, add the following configuration inside your render method of your app/Exceptions/Handler.php
file:
use Harrisonratcliffe\LaravelApiResponses\ApiExceptionHandler;
public function render($request, Throwable $exception)
{
// your other code here
if ($request->expectsJson() || $request->is('api/*')) {
return app(ApiExceptionHandler::class)->renderApiException($exception);
}
// your other code here
}
Here's the modified README to reflect the new option for handling internal server error messages:
The Laravel API Handler package provides a flexible configuration file that allows you to customize default response messages and behaviors. Let's break down each configuration option:
'debug_mode' => end('APP_ENV', false),
- Purpose: Controls whether detailed error information is exposed
- Default: Inherits from Laravel's
APP_ENV
environment variable - Security Warning: 🚨 Only enable in development environments
- Behavior:
- When
true
: Potentially exposes sensitive error details - When
false
: Provides generic, safe error messages
- When
'success_response' => 'API request processed successfully.',
'success_status_code' => 200,
- Success Message: Customizable default message for successful API requests
- Status Code: Standard HTTP 200 OK response
- Customization: Easily modify the default success message to match your application's tone
'http_not_found' => 'The requested resource or endpoint could not be located.',
'unauthenticated' => 'You must be logged in to access this resource. Please provide valid credentials.',
'model_not_found' => 'The requested resource could not be found. This resource doesn\'t exist.',
'unknown_error' => 'An unexpected error has occurred. Please try again later or contact support if the issue persists.',
http_not_found
: Used when a requested endpoint doesn't existunauthenticated
: Triggered for unauthorized access attemptsmodel_not_found
: Dynamic message for missing database records- Provides clarity on what was not found
unknown_error
: Fallback message for unexpected errors
'show_500_error_message' => true,
- Purpose: Controls whether the actual error message from a 500/internal server error is returned.
- Default:
true
(actual error message will be shown) - Behavior:
- When
true
: The detailed error message is returned, which can aid in debugging. - When
false
: Theunknown_error
response will be used instead, maintaining user-friendliness.
- When
- Modify the config file located at
config/api-responses.php
- Tailor messages to match your application's voice
- Keep error messages informative but not overly technical
- Ensure messages are user-friendly and provide clear guidance
// In your controller
use Harrisonratcliffe\LaravelApiResponses\Facades\ApiResponses;
public function index()
{
$data = User::all();
return ApiResponses::success(
'Users retrieved successfully',
$data
);
}
{
"status": "success",
"message": "Users retrieved successfully",
"data": [
{"id": 1, "name": "John Doe"},
{"id": 2, "name": "Jane Smith"}
]
}
use Harrisonratcliffe\LaravelApiResponses\Facades\ApiResponses;
public function store()
{
return ApiResponses::error(
'This virtual machine does not exist',
404,
[
'vm_id' => 12345
],
'https://docs.yourapi.com/errors/some-error'
);
}
{
"status": "error",
"message": "This virtual machine does not exist",
"details": {
"vm_id": 12345
},
"documentation": "https://docs.yourapi.com/errors/some-error"
}
$message
(optional): Custom success message$data
(optional): Response data$statusCode
(optional): HTTP status code (default: 200)
$message
(required): Error description$statusCode
(optional): HTTP error code (default: 400)$details
(optional) Error details$documentation
(optional): Error documentation link$debug
(optional): Additional debug information
Run the test suite using the following command:
Using composer
vendor/bin/pest
Contributions are welcome!
- 🐛 Report Issues: Submit bugs found or log feature requests for the
laravel-api-responses
project. - 💡 Submit Pull Requests: Review open PRs, and submit your own PRs.
Contributing Guidelines
- Fork the Repository: Start by forking the project repository to your github account.
- Clone Locally: Clone the forked repository to your local machine using a git client.
git clone https://github.com/harrisonratcliffe/laravel-api-responses
- Create a New Branch: Always work on a new branch, giving it a descriptive name.
git checkout -b new-feature-x
- Make Your Changes: Develop and test your changes locally.
- Commit Your Changes: Commit with a clear message describing your updates.
git commit -m 'Implemented new feature x.'
- Push to github: Push the changes to your forked repository.
git push origin new-feature-x
- Submit a Pull Request: Create a PR against the original project repository. Clearly describe the changes and their motivations.
- Review: Once your PR is reviewed and approved, it will be merged into the main branch. Congratulations on your contribution!
This project is protected under the MIT License. For more details, refer to the LICENSE file.