willywes/apiresponse

Class to generate a standard structure for api json responses

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

This package is auto-updated.

Last update: 2024-10-12 04:30:00 UTC


README

Latest Version on Packagist Total Downloads StyleCI

Class to generate a standard structure for api json responses.

Installation

Via Composer

$ composer require willywes/apiresponse

Usage

Imports

use Willywes\ApiResponse\ApiResponse;

Functions of Control (HTTP/200 OK)

Default functions that always return a http 200 code, but have a control state.

Params

Functions

Examples

Success example
//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
Error example
//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

Functions with specific HTTP Code

Default functions that returns a specific http code, but in the same way the body responds

Params

Functions Code HTTP 1XX

Functions Code HTTP 2XX

Functions Code HTTP 3XX

Functions Code HTTP 4XX

Functions Code HTTP 5XX

Examples

404 Error example
//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 Error example
//Execution in php
return ApiResponse::Unauthorized();
// or
return ApiResponse::Http401();
//Response
{
   "status": "error",
   "message": "Unauthorized",
   "data": null
}
//HTTP Response 
Status Code: 401 Unauthorized
403 Error example
//Execution in php
return ApiResponse::Forbidden();
// or
return ApiResponse::Http403();
//Response
{
   "status": "error",
   "message": "Forbidden",
   "data": null
}
//HTTP Response 
Status Code: 403 Forbidden

Credits

License

license. Please see the license file for more information.