harrisonratcliffe/laravel-api-responses
最新稳定版本:2.2.3
Composer 安装命令:
composer require harrisonratcliffe/laravel-api-responses
包简介
A Laravel package to easily handle API responses and exceptions
README 文档
README
LARAVEL API RESPONSES
composer require harrisonratcliffe/laravel-api-responses
🔗 Table of Contents
- 📍 Overview
- 👾 Features
- 🚀 Getting Started
- ☑️ Prerequisites
- ⚙ Installation
- 🤖 Usage
- 🧪 Testing
- 🔰 Contributing
- 🎗 License
📍 Overview
A Laravel package to easily handle API responses and exceptions.
👾 Features
- 🌟 Return clean, consistent API responses
- 🛡️ Handle API exceptions with standardized error responses
- 🚀 Easy integration with Laravel 7 to 12
🚀 Getting Started
☑️ Prerequisites
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
⚙️ Installation
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"
API Exception Handler
Note: if you use a different API route path than /api you should adjust the below if statement.
Laravel 11-12
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 })
Laravel 7-10
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:
🔧 Configuration Options
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
'debug_mode' => end('APP_ENV', false),
- Purpose: Controls whether detailed error information is exposed
- Default: Inherits from Laravel's
APP_ENVenvironment variable - Security Warning: 🚨 Only enable in development environments
- Behavior:
- When
true: Potentially exposes sensitive error details - When
false: Provides generic, safe error messages
- When
📡 Default Success Response
'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
🚧 Default Error Messages
'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.',
Error Message Breakdown
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
⚠️ Internal Server Error Message
'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_errorresponse will be used instead, maintaining user-friendliness.
- When
🛠️ Customization Tips
- 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
🤖 Usage
Success Responses
// In your controller use Harrisonratcliffe\LaravelApiResponses\Facades\ApiResponses; public function index() { $data = User::all(); return ApiResponses::success( 'Users retrieved successfully', $data ); }
Example Success Response
{
"status": "success",
"message": "Users retrieved successfully",
"data": [
{"id": 1, "name": "John Doe"},
{"id": 2, "name": "Jane Smith"}
]
}
Error Responses
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' ); }
Example Error Response
{
"status": "error",
"message": "This virtual machine does not exist",
"details": {
"vm_id": 12345
},
"documentation": "https://docs.yourapi.com/errors/some-error"
}
Method Signatures
successResponse()
$message(optional): Custom success message$data(optional): Response data$statusCode(optional): HTTP status code (default: 200)
errorResponse()
$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
🧪 Testing
Run the test suite using the following command:
Using composer
vendor/bin/pest
🔰 Contributing
Contributions are welcome!
- 🐛 Report Issues: Submit bugs found or log feature requests for the
laravel-api-responsesproject. - 💡 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!
🎗 License
This project is protected under the MIT License. For more details, refer to the LICENSE file.
统计信息
- 总下载量: 101
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 0
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2025-03-21