dotcubed.io/laravel-api-response

Laravel API Response

0.2 2024-04-27 22:05 UTC

This package is auto-updated.

Last update: 2024-04-27 22:07:20 UTC


README

What is this repository for?

This repo formats the response for API endpoints displaying information that is crucial for debugging and day-to-day operations.

How do I get set up?

Install the package and both middleware and response facade will be automatically discovered.

Behind the scenes

When a request is triggered, the following happens:

  • a middleware injects a requestId in the header so that all responses will have it available
  • the response facade kicks in and checks if the request expects a json response or is ajax which defines an API endpoint
  • at this point the response will then format all the data that is needs to be outputted

Usage

There are 5 methods available in the package that will format a Response. One is the main method and the other 4 are wrappers for simpler calls. The following methods are available:

methodparametersdescription
getJsonResponserequestStatus : success, failure, warning
message : an optional string message
data : data to be returned
statusCode : either the same as used in the header or an internal/alteranate
requestId : same used in the header
errorData : error trace array
errorBag : error list as piped form a Form Request
Fully-controlled response
successdata : data to be returned
message : a string message
responseCode : defaults 200
simple version
successMessagemessage : a string messagemessage-only response with an HTTP 200 code
failuredata : data to be returned
message : a string message
responseCode : defaults to 200
failureMessagemessage : a string messagemessage-only failure response with a HTTP 400 code

Examples

Code

$data = $model->get(1);
return Response::success($data);

Response

{
    "status": "success",
    "statusCode": 200,
    "data": {
        "user": {
            "name": "John Smith"
        }
    },
    "requestId": "662d5de536b97",
    "timestamp": 1714249189.23148
}