Looking to hire Laravel developers? Try LaraJobs

laravel-api-response maintained by dotcubed.io

Description
Laravel API Response
Author
Last update
2024/04/28 00:05 (dev-main)
License
Downloads
677

Comments
comments powered by Disqus

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:

method parameters description
getJsonResponse requestStatus : success, failure, warningmessage : an optional string messagedata : data to be returnedstatusCode : either the same as used in the header or an internal/alteranaterequestId : same used in the headererrorData : error trace array errorBag : error list as piped form a Form Request Fully-controlled response
success data : data to be returnedmessage : a string messageresponseCode : defaults 200 simple version
successMessage message : a string message message-only response with an HTTP 200 code
failure data : data to be returnedmessage : a string messageresponseCode : defaults to 200
failureMessage message : a string message message-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
}