creativecrafts/laravel-api-response
Composer 安装命令:
composer require creativecrafts/laravel-api-response
包简介
Laravel API Response is a powerful and flexible package that provides a standardized way to structure API responses in Laravel applications. It offers a range of features to enhance your API development experience, including consistent response formatting, conditional responses, pagination support,
README 文档
README
Laravel API Response is a powerful and flexible package that provides a standardized way to structure API responses in Laravel applications. It offers a range of features to enhance your API development experience, including consistent response formatting, conditional responses, pagination support, rate limiting, and more.
Table of Contents
1. [Installation](#installation)
2. [Configuration](#configuration)
3. [Basic Usage](#basic-usage)
4. [Feature](#feature)
- [Success Response](#success-response)
- [Error Response](#error-response)
- [Conditional Response](#conditional-response)
- [Pagination](#pagination)
- [Rate Limiting](#rate-limiting)
- [Response Compression](#response-compression)
- [Localization](#localization)
- [HATEOAS Links](#hateoas-links)
- [Logging](#logging)
5. [Advanced Usage](#advanced-usage)
6. [Testing](#testing)
7. [Changelog](#changelog)
8. [Contributing](#contributing)
9. [Security Vulnerabilities](#security-vulnerabilities)
10. [Credits](#credits)
11. [License](#license)
1. Installation
You can install the package via composer:
composer require creativecrafts/laravel-api-response
2. Configuration
The package comes with a default configuration file that you can publish to your application using the following command:
php artisan vendor:publish --tag=api-response-config
This will create a laravel-api-response.php file in your config directory. You can customize various aspects of the package behavior in this file.
3. Basic Usage
There are two ways to use the Laravel API Response in your controllers:
Using Dependency Injection
You can inject the LaravelApi class:
use CreativeCrafts\LaravelApiResponse\LaravelApi; class UserController extends Controller { protected $api; public function __construct(LaravelApi $api) { $this->api = $api; } public function index() { $users = User::all(); return $this->api->successResponse('Users retrieved successfully', $users); } }
Using the Facade
For a more Laravel-like experience, you can use the LaravelApiResponse facade:
use CreativeCrafts\LaravelApiResponse\Facades\LaravelApiResponse; class UserController extends Controller { public function index() { $users = User::all(); return LaravelApiResponse::successResponse('Users retrieved successfully', $users); } }
4. Feature
The Laravel API Response package provides a range of features to help you build robust and reliable APIs. Here are some of the key features:
Success Responses
To return a success response:
return $this->api->successResponse('Operation successful', $data);
Error Responses
To return an error response:
return $this->api->errorResponse('An error occurred', $errorCode, $statusCode);
Conditional Responses
For responses that support caching and conditional requests:
return $this->api->conditionalResponse($data, 'Data retrieved successfully');
This method automatically handles ETag and Last-Modified headers for efficient caching.
Pagination
The package supports Laravel's pagination:
$users = User::paginate(15); return $this->api->paginatedResponse('Users retrieved successfully', $users);
Rate Limiting
Rate limiting is automatically applied to API routes. You can configure the rate limit in the laravel-api-response.php config file:
'rate_limit_max_attempts' => env('API_RATE_LIMIT_MAX_ATTEMPTS', 60), 'rate_limit_decay_minutes' => env('API_RATE_LIMIT_DECAY_MINUTES', 1),
Response Compression
Response compression can be enabled or disabled in the config:
'enable_compression' => env('API_RESPONSE_COMPRESSION', true),
Localization
The package supports message localization. Use the localize method to translate messages:
$message = $this->api->localize('messages.welcome');
HATEOAS Links
You can include HATEOAS links in your responses:
$links = [ 'self' => ['href' => '/api/users/1'], 'posts' => ['href' => '/api/users/1/posts'], ]; return $this->api->successResponse('User retrieved', $userData, 200, [], $links);
Logging
API responses are logged to a dedicated channel. You can configure the channel in the config file:
'log_channel' => 'api',
Exception Handling
The package includes a custom exception handler that automatically formats exceptions into consistent API responses. This is enabled by default and can be configured in the config file:
'use_exception_handler' => env('API_USE_EXCEPTION_HANDLER', true),
When enabled, the exception handler will automatically catch exceptions and format them into API responses with appropriate status codes. For example:
- Validation exceptions will be formatted as validation error responses
- Model not found exceptions will be formatted as 404 error responses
- Authentication exceptions will be formatted as 401 error responses
- Authorization exceptions will be formatted as 403 error responses
This ensures consistent error responses across your API without requiring extra code in your controllers.
5. Advanced Usage
The Laravel API Response package provides a range of advanced features to help you build robust and reliable APIs. Here are some of the key features:
Custom Response Structure
You can customize the response structure in the config file:
'response_structure' => [ 'success_key' => 'success', 'message_key' => 'message', 'data_key' => 'data', 'errors_key' => 'errors', 'error_code_key' => 'error_code', 'meta_key' => 'meta', 'links_key' => '_links', 'include_api_version' => true, ],
Filtering Response Fields
You can filter the fields returned in the response:
$fields = ['id', 'name', 'email']; return $this->api->successResponse('User data', $userData, 200, [], [], $fields);
Custom Status Codes
You can specify custom HTTP status codes for your responses:
return $this->api->successResponse('Resource created', $newResource, 201);
Extending with Custom Methods
The LaravelApi class uses Laravel's Macroable trait, allowing you to add custom response methods at runtime:
use CreativeCrafts\LaravelApiResponse\LaravelApi; use Illuminate\Support\Facades\Response; LaravelApi::macro('teapotResponse', function ($message = "I'm a teapot") { return Response::json(['message' => $message], 418); }); // Then in your controller: return $this->api->teapotResponse(); // Or using the facade: return LaravelApiResponse::teapotResponse("Custom teapot message");
This makes it easy to extend the package with your own custom response types without modifying the core code.
Version 2: Breaking Changes
Version 2 of the package introduces one breaking change.
- createdResponse method has been removed. Use successResponse instead.
Testing
composer test
Changelog
Please see CHANGELOG for more information on what has changed recently.
Contributing
Please see CONTRIBUTING for details.
Security Vulnerabilities
Please review our security policy on how to report security vulnerabilities.
Credits
License
The MIT License (MIT). Please see License File for more information.
creativecrafts/laravel-api-response 适用场景与选型建议
creativecrafts/laravel-api-response 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 1.45k 次下载、GitHub Stars 达 1, 最近一次更新时间为 2023 年 12 月 07 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「laravel」 「laravel-api-response」 「creativeCrafts」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 creativecrafts/laravel-api-response 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 creativecrafts/laravel-api-response 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 creativecrafts/laravel-api-response 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
This is a handy package the can send email via AWS SES
A simple package that will provide a fluent api to interact with third party authentication providers
A handy package to access and interact with OpenAi endpoint
A handy package to paginate laravel collection
API Response trait for Laravel, which helps you to create consistent and standardized API responses in your Laravel applications.
A simple package to send sms messages using twillio
统计信息
- 总下载量: 1.45k
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 1
- 点击次数: 11
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2023-12-07