surazdott/api-response
Composer 安装命令:
composer require surazdott/api-response
包简介
Laravel package for HTTP JSON response for API.
README 文档
README
Laravel API Response
Laravel API Response package simplifies the process of generating standardized JSON responses in Laravel applications. It provides a consistent and intuitive API through the package, offering a variety of methods to manage different types of HTTP responses effectively.
Installation
Requires PHP 8.1+
To install the package, you can use Composer:
composer require surazdott/api-response
You can publish the config, languages and resources from with the help of command.
php artisan vendor:publish --tag=api-response
Basic usage
After installing the package, you can use the Api facade or helper function to generate JSON responses in your controllers or anywhere within your application. The following methods are available:
Facade
Generates a generic JSON response with facade.
use Api; .... public function index() { $posts = Post::take(10)->get(); return Api::response('Data fetched successfully', $posts); }
Helper function
Generates a generic JSON response with helper function.
public function index() { $posts = Post::take(10)->get(); return api()->response('Data fetched successfully', $posts); }
This is the result.
{
"success": true,
"message": "Data fetched successfully",
"data": [
{"title": "Post Title", ...}
]
}
Methods
response
Generates a generic JSON response with a customizable status code.
response(string $message, mixed $data = [], int $status = 200)
return api()->response('Operation completed successfully', $data = [], $status = 200); // Result { "success": true, "message": "Operation completed successfully", "data": [] }
success
Method for a successful operation with HTTP status code 200.
success(string $message, mixed $data = [])
public function index() { $users = User::take(2)->get(); return api()->success('Request processed successfully.', $users); } // Result { "success": true, "message": "Request processed successfully.", "data": [ { "id": 1", "name": "Suraj....", }, { "id": 2", "name": "Rabin....", } ] }
paginate
Return for a successful operation with HTTP paginated data.
paginate(string $message, mixed $data = [])
public function index() { $users = UserResource::collection(User::active()->paginate(10)); return api()->paginate('Data fetched successfully.', $users); } // Result { "success": true, "message": "Data fetched successfully.", "data": [ { "id": 1", "name": "Suraj....", }, { "id": 2", "name": "Rabin....", } ], "links": { "first": "http://example.com/api/v1/users?page=1", "last": "http://example.com/api/v1/users?page=1", "prev": null, "next": null }, "meta": { "total": 0, "current_page": 1, "total_pages": 1, "per_page": 10 } }
created
Returns a response indicating that a resource has been successfully created with HTTP status code 201.
created(string $message, mixed $data = [])
public function store() { $user = User::create(['name' => 'Suraj']); return api()->created('Resource created successfully', $user); } // Result { "success": true, "message": "Resource created successfully", "data": [ { "id": 1, "name": "Suraj Datheputhe", } ] }
error
Returns an error response with HTTP status code 4xx.
error(string $message, int $status = 400)
public function foo() { return api()->error('Bad request'); } // Result { "success": false, "message": "Bad request" }
unauthorized
Returns an unauthorized response with HTTP status code 401.
unauthorized(string $message)
public function edit() { if ($user->isNotAdmin()) { return api()->unauthorized('Authentication is required to access this resource.'); } } // Result { "success": false, "message": "Authentication is required to access this resource" }
forbidden
Returns an unauthorized response with HTTP status code 401.
forbidden(string $message)
public function edit() { if ($user->isNotAdmin()) { return api()->unauthorized('You do not have permission to access this resource.'); } } // Result { "success": false, "message": "You do not have permission to access this resource" }
notFound
Returns a not found response with HTTP status code 404.
notFound(string $message)
public function edit() { $post = Post::find(1); if (! $post) { return api()->notFound('Requested resource could not be found'); } } // Result { "success": false, "message": "Requested resource could not be found" }
notAllowed
Returns a method not allowed response with HTTP status code 405.
notAllowed(string $message)
Route::fallback(function() { return api()->notAllowed('Method type is not currently supported'); }); // Result { "success": false, "message": "Method type is not currently supporte." }
validation
Generates a response indicating validation errors with HTTP status code 400.
validation(string $message, mixed $errors = [])
public function login() { $validator = Validator::make($request->all(), [ 'email' => 'required', 'password' => 'required', ]); if ($validator->fails()) { return api()->validation('Validation failed for the request.', $validator->errors()); } } // Result { "success": false, "message": "Validation failed for the request", "errors": { "password": [ "The password field is required." ] } }
serverError
Returns an error response with HTTP status code 4xx.
serverError(string $message, int $status = 500)
public function index() { try { $users = \App\Models\User::find($id); // Undefined $id } catch (\Exception $e) { return api()->error('Invalid syntax for this request was provided'); } } // Result { "success": false, "message": "Invalid syntax for this request was provided" }
Note: API response messages are predefined and can be changed from parameters or from the language file.
Request Validation
Laravel's request validation can be used for both web and API. You can call the trait
SurazDott\ApiResposne\Concerns\HasApiResponse;
<?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; use SurazDott\ApiResposne\Concerns\HasApiResponse; class UserStoreRequest extends FormRequest { use HasApiResponse; /** * Determine if the user is authorized to make this request. */ public function authorize(): bool { return true; } /** * Get the validation rules that apply to the request. * * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string> */ public function rules(): array { return [ 'name' => ['required', 'string', 'max:255'], ]; } } // Result { "success": false, "message": "Validation failed for the request", "errors": { "name": [ "The name field is required." ] } }
API Exceptions
If you want to throw the custom exceptionl, you can use the following classes:
ApiResponseException(string $message, ?int status)
use SurazDott\ApiResponse\Exceptions\ApiResponseException; public function login(Request $request) { if ($user->isNotAdmin()) { throw new ApiResponseException('User must be an admin', 403); } } // Result { "success": false, "message": "User must be an admin" }
ApiValidationException(mixed $errors, ?string $message)
use SurazDott\ApiResponse\Exceptions\ApiValidationException; public function validation(Request $request) { $validator = Validator::make($request->all(), [ 'email' => ['required', 'email', 'max:255', 'unique:users,email'], ]); if ($validator->fails()) { throw new ApiValidationException('Validation failed for the request', $validator->errors()); } } // Result { "success": false, "message": "Validation failed for the request", "errors": { "email": [ "The email field is required." ] } }
Contributing
If you find any issues or have suggestions for improvements, feel free to open an issue or create a pull request. Contributions are welcome!
License
This package is open-sourced software licensed under the MIT license.
surazdott/api-response 适用场景与选型建议
surazdott/api-response 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 58 次下载、GitHub Stars 达 9, 最近一次更新时间为 2024 年 09 月 19 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「laravel」 「api-response」 「surazdott」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 surazdott/api-response 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 surazdott/api-response 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 surazdott/api-response 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Symfony bundle providing a typed, reusable view layer for building JSON API responses with automatic property binding and cache-warmed serialization
Alfabank REST API integration
Laravel API response helpers with server-configured payload compression and encryption.
The ApiResponse package is a simple yet powerful Laravel package designed to streamline the process of formatting API responses. It provides a convenient way to structure and return JSON responses in a consistent format for both success and error scenarios.
API Response trait for Laravel, which helps you to create consistent and standardized API responses in your Laravel applications.
A Laravel package designed to simplify the creation of structured and formatted API responses (JSON, XML) with custom status codes, messages, and data. XML support is currently under construction.
统计信息
- 总下载量: 58
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 9
- 点击次数: 7
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2024-09-19
