jornatf / laravel-api-json-response
一个用于返回API JSON响应的Laravel扩展包。
v1.1.0
2023-04-23 19:54 UTC
Requires
- php: ^8.1
- illuminate/contracts: ^10.0
Requires (Dev)
- laravel/pint: ^1.0
- nunomaduro/collision: ^7.9
- orchestra/testbench: ^8.0
- pestphp/pest: ^2.0
- pestphp/pest-plugin-arch: ^2.0
- pestphp/pest-plugin-laravel: ^2.0
This package is auto-updated.
Last update: 2024-09-09 18:01:42 UTC
README
一个用于返回API JSON响应的Laravel扩展包。在某些方法中,您可以返回酷炫的JSON响应以供您的API使用。
如果您喜欢这个扩展包,可以给我买杯咖啡 ☕️
安装
通过composer
composer require jornatf/laravel-api-json-response
使用方法
示例1
此示例向您展示了如何使用基本必需的方法。
<?php namespace App\Http\Controllers; use App\Models\Post; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use Illuminate\Support\Facades\Validator; class PostController extends Controller { public function store(Request $request) { $validator = Validator::make($request->all(), [ 'title' => 'required|unique:posts|max:255', 'body' => 'required', ]); if ($validator->fails()) { // Status code 400 for "Bad Request" return ApiResponse::response(400) ->addDetails($validator->errors()) ->json(); } $post = Post::create($validator->validated()); // Status code 200 for "Ok" or 201 for "Created" return ApiResponse::response(201) ->addDatas($post) ->json(); } }
成功响应
{
"success": {
"status": 201,
"message": "Created",
"data": {
"id": 1,
"title": "Morbi in diam id dolor vehicula finibus",
"content": "<p>Lorem ipsum dolor sit amet, ...</p>",
"created_at": "2023-04-20 00:00:00",
"updated_at": "2023-04-20 00:00:00"
}
}
}
错误响应
{
"error": {
"status": 404,
"message": "Not Found"
}
}
示例2
此示例向您展示了如何使用一个方法查找模型,并在一行代码中返回JSON响应。
<?php namespace App\Http\Controllers; use App\Models\Post; use App\Http\Controllers\Controller; class PostController extends Controller { public function show(int $post_id) { return ApiResponse::find(Post::class, $post_id)->json(); } }
如果找到模型
{
"success": {
"status": 200,
"message": "Post Found",
"data": {
"id": 1,
"title": "Morbi in diam id dolor vehicula finibus",
"content": "<p>Lorem ipsum dolor sit amet, ...</p>",
"created_at": "2023-04-20 00:00:00",
"updated_at": "2023-04-20 00:00:00"
}
}
}
否则
{
"error": {
"status": 404,
"message": "Post Not Found"
}
}
文档
可用方法
<?php // First, you can instantiate response with a status code (required): $response = ApiResponse::response(int $statusCode); // or directly find a model by id: $response = ApiResponse::find(Model::class, int $id); // To add custom message: $response->addMessage(string $message); // To add datas to return when success: $response->addDatas(array $datas); // To add details (e.g. validator errors) when error: $response->addDetails(mixed $details); // or $response->addDetails(array $details); $response->addDetails(array $details); // Last, formate response into json (required): $response->json()
可用状态码
测试
composer test
更新日志
请参阅更新日志获取最近更改的更多信息。
贡献
请随意为此项目做出贡献,以添加新功能或修复错误 👍
鸣谢
许可
MIT许可(MIT)。
请参阅许可文件获取更多信息。