willywes/apiresponse

用于生成 API JSON 响应标准结构的类

v1.7.0 2023-09-12 02:08 UTC

This package is auto-updated.

Last update: 2024-09-12 04:17:16 UTC


README

Latest Version on Packagist Total Downloads StyleCI

用于生成 API JSON 响应标准结构的类。

安装

通过 Composer

$ composer require willywes/apiresponse

用法

导入

use Willywes\ApiResponse\ApiResponse;

控制函数(HTTP/200 OK)

默认函数始终返回 HTTP 200 状态码,但具有控制状态。

参数

函数

示例

成功示例
//Execution in php
return ApiResponse::JsonSuccess([
        'user' => User::first(),
        'roles' => Role::all(),
    ]);
//Response
{
    "status":"success",
    "title":"Operación Exitosa.",
    "message": null,
    "data":{
        "user":{
            "id":1,
            "full_name":"John Smith",
            "email":"jsmith@test.cl",
            "role_id":1
        },
        "roles":[
            {
                "id":1,
                "name":"God Admin"
            },
            {
                "id":2,
                "name":"Administrator"
            }
        ]
    }
}
//HTTP Response 
Status Code: 200 OK
错误示例
//Execution in php
return ApiResponse::JsonError(null, 'something has gone wrong!', 'oops');
//Response
{
    "status":"error",
    "title":"oops",
    "message":"something has gone wrong!",
    "data": null
}
//HTTP Response 
Status Code: 200 OK

具有特定 HTTP 状态码的函数

默认函数返回特定 HTTP 状态码,但以相同方式响应体

参数

HTTP 1XX 状态码函数

HTTP 2XX 状态码函数

HTTP 3XX 状态码函数

HTTP 4XX 状态码函数

HTTP 5XX 状态码函数

示例

404 错误示例
//Execution in php
return ApiResponse::NotFound(null, 'object not found!');
// or
//Execution in php without params
return ApiResponse::NotFound();
// or
return ApiResponse::Http404();
//Response
{
   "status": "error",
   "message": "Not Found",
   "data": null
}
//HTTP Response 
Status Code: 404 Not Found
401 错误示例
//Execution in php
return ApiResponse::Unauthorized();
// or
return ApiResponse::Http401();
//Response
{
   "status": "error",
   "message": "Unauthorized",
   "data": null
}
//HTTP Response 
Status Code: 401 Unauthorized
403 错误示例
//Execution in php
return ApiResponse::Forbidden();
// or
return ApiResponse::Http403();
//Response
{
   "status": "error",
   "message": "Forbidden",
   "data": null
}
//HTTP Response 
Status Code: 403 Forbidden

致谢

许可协议

许可协议。请参阅许可文件以获取更多信息。