surazdott / api-response
Laravel API HTTP JSON响应包。
Requires
- php: ^8.1
Requires (Dev)
- orchestra/testbench: ^8.26
- phpstan/phpstan: ^1.12
- phpunit/phpunit: ^10.5
- squizlabs/php_codesniffer: ^3.10
This package is auto-updated.
Last update: 2024-09-25 14:17:44 UTC
README
Laravel API Response
Laravel API Response包简化了在Laravel应用程序中生成标准化JSON响应的过程。它通过包提供一致的直观API,提供各种方法来有效管理不同类型的HTTP响应。
安装
需要PHP 8.1+
要安装此包,您可以使用Composer
composer require surazdott/api-response
您可以使用命令发布配置、语言和资源。
php artisan vendor:publish --tag=api-response
基本用法
安装包后,您可以使用Api门面或辅助函数在控制器或应用程序中的任何位置生成JSON响应。以下方法可用
门面
使用门面生成通用JSON响应。
use Api; .... public function index() { $posts = Post::take(10)->get(); return Api::response('Data fetched successfully', $posts); }
辅助函数
使用辅助函数生成通用JSON响应。
public function index() { $posts = Post::take(10)->get(); return api()->response('Data fetched successfully', $posts); }
这是结果。
{ "success": true, "message": "Data fetched successfully", "data": [ {"title": "Post Title", ...} ] }
方法
response
生成带有可定制状态码的通用JSON响应。
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
成功操作的快捷方式,带有HTTP状态码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....", } ] }
created
返回一个响应,指示已成功创建资源,带有HTTP状态码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
返回带有HTTP状态码4xx的错误响应。
error(string $message, int $status = 400)
public function foo() { return api()->error('Bad request'); } // Result { "success": false, "message": "Bad request" }
unauthorized
返回带有HTTP状态码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
返回带有HTTP状态码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
返回带有HTTP状态码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
返回带有HTTP状态码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
生成带有HTTP状态码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." ] } }
unprocessable
生成带有HTTP状态码422的不可处理响应。
unprocessable(string $message, mixed $errors = [])
$errors = ['details' => 'Server was unable to process the request']; return api()->unprocessable($errors); // Result { "success": false, "message": "Server was unable to process the request", "errors": { "details": "Invalid request data" } }
serverError
返回带有HTTP状态码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" }
注意:API响应消息是预定义的,可以通过参数或从语言文件进行更改。
请求验证
Laravel的请求验证可用于Web和API。您可以调用特质
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异常
如果您想抛出自定义异常,可以使用以下类
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." ] } }
贡献
如果您发现任何问题或对改进有建议,请随意提出问题或创建pull request。欢迎贡献!
许可证
此包是开源软件,许可协议为MIT许可。