greelogix/api-response-formatter
最新稳定版本:v1.0.0
Composer 安装命令:
composer require greelogix/api-response-formatter
包简介
A Laravel package that standardizes API responses across projects with support for multiple formats (custom, jsend, json_api) and Laravel Resources.
README 文档
README
A Laravel package that standardizes API responses across projects with support for multiple formats (custom, jsend, json_api) and Laravel Resources.
Features
- ✅ Simple to use - Works out-of-the-box after installation
- ✅ Multiple formats - Support for custom, JSend, and JSON:API formats
- ✅ Laravel Resources - Automatic detection and formatting of Laravel API Resources
- ✅ Configurable - All options configurable via config file and environment variables
- ✅ Consistent structure - Provides consistent response structure across your API
- ✅ Default status codes - Configurable default status codes with per-call overrides
- ✅ Auto messages - Automatic message generation based on response type
- ✅ Pagination support - Automatic pagination metadata extraction and formatting
- ✅ Laravel 8, 9, 10, 11 - Full support for multiple Laravel versions
Installation
Install the package via Composer:
composer require greelogix/api-response-formatter
The package will automatically register its service provider.
Configuration
Publish the configuration file:
php artisan vendor:publish --tag=gl-api-response-formatter-config
This will create config/gl-api-response-formatter.php with the following default configuration:
return [ 'format' => 'custom', // default format 'messages_enabled' => true, 'auto_messages' => true, 'message_single' => 'Data fetched successfully.', 'message_collection' => 'Records fetched successfully.', 'message_paginated' => 'Paginated results fetched successfully.', 'message_error' => 'Something went wrong.', 'pagination_enabled' => true, 'pagination_key' => 'pagination', 'resource_support' => true, 'status_codes' => [ 'success' => 200, 'created' => 201, 'error' => 400, 'validation' => 422, 'not_found' => 404, 'unauthorized' => 401, ], ];
Environment Variables
All configuration values can be overridden using environment variables with the GL_API_RESPONSE_FORMATTER_* prefix:
GL_API_RESPONSE_FORMATTER_FORMAT=custom GL_API_RESPONSE_FORMATTER_MESSAGES_ENABLED=true GL_API_RESPONSE_FORMATTER_AUTO_MESSAGES=true GL_API_RESPONSE_FORMATTER_MESSAGE_SINGLE="Data fetched successfully." GL_API_RESPONSE_FORMATTER_MESSAGE_COLLECTION="Records fetched successfully." GL_API_RESPONSE_FORMATTER_MESSAGE_PAGINATED="Paginated results fetched successfully." GL_API_RESPONSE_FORMATTER_MESSAGE_ERROR="Something went wrong." GL_API_RESPONSE_FORMATTER_PAGINATION_ENABLED=true GL_API_RESPONSE_FORMATTER_PAGINATION_KEY=pagination GL_API_RESPONSE_FORMATTER_RESOURCE_SUPPORT=true GL_API_RESPONSE_FORMATTER_STATUS_SUCCESS=200 GL_API_RESPONSE_FORMATTER_STATUS_CREATED=201 GL_API_RESPONSE_FORMATTER_STATUS_ERROR=400 GL_API_RESPONSE_FORMATTER_STATUS_VALIDATION=422 GL_API_RESPONSE_FORMATTER_STATUS_NOT_FOUND=404 GL_API_RESPONSE_FORMATTER_STATUS_UNAUTHORIZED=401
Usage
Basic Usage
Using the Static Facade
use GreeLogix\ApiResponseFormatter\ApiResponse; // Success response return ApiResponse::success(User::all()); // With custom message return ApiResponse::success($user, 'User retrieved successfully.'); // With custom status return ApiResponse::success($user, status: 202); // With meta data return ApiResponse::success($user, meta: ['version' => '1.0']); // Error response return ApiResponse::error('User not found', status: 404); // Validation error return ApiResponse::validationError($validator->errors()->toArray()); // Not found return ApiResponse::notFound('Resource not found'); // Unauthorized return ApiResponse::unauthorized('Unauthorized access'); // Created response return ApiResponse::created($newUser, 'User created successfully.');
Using the Trait in Controllers
use GreeLogix\ApiResponseFormatter\ApiResponseTrait; use Illuminate\Http\Request; class UserController extends Controller { use ApiResponseTrait; public function index() { $users = User::paginate(15); return $this->successResponse($users); } public function show($id) { $user = User::find($id); if (!$user) { return $this->errorResponse('User not found', status: 404); } return $this->successResponse($user); } public function store(Request $request) { $validator = Validator::make($request->all(), [ 'name' => 'required', 'email' => 'required|email', ]); if ($validator->fails()) { return $this->errorResponse( 'Validation failed', $validator->errors()->toArray(), status: 422 ); } $user = User::create($request->all()); return $this->successResponse($user, 'User created successfully.', status: 201); } }
Using the Exception
use GreeLogix\ApiResponseFormatter\Exceptions\ApiException; // In your controller or service if (!$user) { throw new ApiException('User not found', statusCode: 404); } // With validation errors throw new ApiException( 'Validation failed', statusCode: 422, errors: $validator->errors()->toArray() );
Laravel Resources Support
The package automatically detects and formats Laravel API Resources:
use App\Http\Resources\UserResource; use GreeLogix\ApiResponseFormatter\ApiResponse; // Single resource $user = User::find(1); return ApiResponse::success(new UserResource($user)); // Resource collection $users = User::all(); return ApiResponse::success(UserResource::collection($users));
Pagination Support
The package automatically detects and formats paginated results:
use GreeLogix\ApiResponseFormatter\ApiResponse; // Paginated response $users = User::paginate(15); return ApiResponse::success($users);
This will automatically include pagination metadata in the response.
Response Formats
Custom Format (Default)
Success Response:
{
"success": true,
"message": "Data fetched successfully.",
"data": {
"id": 1,
"name": "John Doe"
}
}
Collection Response:
{
"success": true,
"message": "Records fetched successfully.",
"data": [
{"id": 1, "name": "John Doe"},
{"id": 2, "name": "Jane Doe"}
]
}
Paginated Response:
{
"success": true,
"message": "Paginated results fetched successfully.",
"data": [
{"id": 1, "name": "John Doe"},
{"id": 2, "name": "Jane Doe"}
],
"pagination": {
"current_page": 1,
"per_page": 15,
"total": 100,
"last_page": 7,
"from": 1,
"to": 15
}
}
Error Response:
{
"success": false,
"message": "Something went wrong.",
"errors": {
"email": ["The email field is required."]
}
}
JSend Format
To use JSend format, set format to jsend in your config:
'format' => 'jsend',
Success Response:
{
"status": "success",
"data": {
"id": 1,
"name": "John Doe"
},
"message": "Data fetched successfully."
}
Fail Response (4xx):
{
"status": "fail",
"message": "Validation failed",
"data": {
"email": ["The email field is required."]
}
}
Error Response (5xx):
{
"status": "error",
"message": "Internal server error"
}
JSON:API Format
To use JSON:API format, set format to json_api in your config:
'format' => 'json_api',
Success Response:
{
"data": {
"id": 1,
"name": "John Doe"
},
"meta": {
"message": "Data fetched successfully."
}
}
Error Response:
{
"errors": [
{
"status": "422",
"title": "Validation Error",
"detail": "The email field is required.",
"source": {
"pointer": "/data/attributes/email"
}
}
]
}
Status Codes
Default status codes are configured in the config file and can be overridden per response:
// Uses default status code from config (200) return ApiResponse::success($data); // Override status code return ApiResponse::success($data, status: 202); // Uses default created status code (201) return ApiResponse::created($data); // Override created status code return ApiResponse::created($data, status: 201);
Messages
Auto Messages
When auto_messages is enabled (default), the package automatically generates messages based on response type:
- Single item →
message_single - Collection →
message_collection - Paginated →
message_paginated - Error →
message_error
Custom Messages
You can provide custom messages per response:
return ApiResponse::success($user, 'User retrieved successfully.');
Disable Messages
To disable messages globally:
'messages_enabled' => false,
Or disable auto messages but allow manual messages:
'auto_messages' => false,
Pagination
Pagination is automatically detected and formatted. To disable pagination metadata:
'pagination_enabled' => false,
To change the pagination key:
'pagination_key' => 'meta', // Changes 'pagination' to 'meta'
Advanced Usage
Using ApiResponseManager Directly
use GreeLogix\ApiResponseFormatter\ApiResponseManager; $manager = app(ApiResponseManager::class); return $manager->success($data, 'Custom message', 200, ['version' => '1.0']);
Custom Formatter
You can create your own formatter by implementing FormatterInterface:
use GreeLogix\ApiResponseFormatter\Formatters\FormatterInterface; class MyCustomFormatter implements FormatterInterface { public function formatSuccess($data, ?string $message = null, ?array $meta = null, ?array $pagination = null): array { // Your custom format logic } public function formatError(?string $message = null, ?array $errors = null): array { // Your custom error format logic } }
Testing
use GreeLogix\ApiResponseFormatter\ApiResponse; // In your tests $response = ApiResponse::success(['test' => 'data']); $response->assertStatus(200) ->assertJson([ 'success' => true, 'data' => ['test' => 'data'] ]);
Requirements
- PHP >= 8.1
- Laravel >= 8.0
License
This package is open-sourced software licensed under the MIT license.
Support
For issues, questions, or contributions, please visit the GitHub repository.
Changelog
Please see CHANGELOG.md for more information on what has changed recently.
统计信息
- 总下载量: 1
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 6
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2026-01-22