raditzfarhan/laravel-api-response

Laravel and Lumen API response transformer

Installs: 3 025

Dependents: 0

Suggesters: 0

Security: 0

Stars: 4

Watchers: 1

Forks: 1

Open Issues: 0

Type:laravel-package

v1.2.0 2024-03-05 02:52 UTC

This package is auto-updated.

Last update: 2024-12-05 04:24:31 UTC


README

Laravel API Response

Latest Stable Version Total Downloads License StyleCI

Laravel and Lumen API response transformer/formatter.

Requirements

  • PHP ^7.4 | ^8.0
  • Laravel 7, 8, 9 or 10

Installation

Via Composer

$ composer require raditzfarhan/laravel-api-response

Configuration

The Laravel and Lumen configurations vary slightly, so here are the instructions for each of the frameworks.

Laravel

Edit the config/app.php file and add the following line to register the service provider:

'providers' => [
    ...
    RaditzFarhan\ApiResponse\ApiResponseServiceProvider::class,
    ...
],

Tip: If you're on Laravel version 5.5 or higher, you can skip this part of the setup in favour of the Auto-Discovery feature.

Lumen

Edit the bootstrap/app.php file and add the following line to register the service provider:

...
$app->register(RaditzFarhan\ApiResponse\ApiResponseServiceProvider::class);
...

You will also need to enable Facades in bootstrap/app.php:

..
$app->withFacades(true, [
    RaditzFarhan\ApiResponse\Facades\ApiResponse::class => 'ApiResponse'
]);
...

Usage

Example usage as below snippet:

// Success response

// using service container
$response = app('ApiResponse')->success();

// using alias
$response = \ApiResponse::success();

// Failed response
$response = \ApiResponse::failed();

The response will return a Illuminate\Http\Response instance just like when u call response() helper method.

By default, success will use http 200 code if not set, and failed will use http 500 code if not set.

Typical response content as follow:

Success

{
    "status": true,
    "http_code": 200,
    "message": "Success."
}

Failed

{
    "status": false,
    "http_code": 500,
    "message": "Failed."
}

Add/Change payload data by chaining more methods as below:

// Example #1
return ApiResponse::httpCode(201)->message('Created new record!')->data(['name' => 'Raditz Farhan', 'country' => 'MY'])->success();

// or can be shorten to
return ApiResponse::created(['name' => 'Raditz Farhan', 'country' => 'MY']);

// Example #2
return ApiResponse::httpCode(422)->message('Validation error!')->errors(['name' => ['Name field is required.']])->failed();

// or can be shorten to
return ApiResponse::validationError(['name' => ['Name field is required.']]);

Above call will result in below:

Example #1

{
    "status": true,
    "http_code": 201,
    "message": "Created new record!",
    "data": {
        "name": "Raditz Farhan",
        "country": "MY"
    }    
}

Example #2

{
    "status": false,
    "http_code": 422,
    "message": "Validation error!",
    "errors": {
        "name": [
            "Name field is required."
        ]
    },
}

Use collection method to return paginate result that includes meta and links attribute:

return ApiResponse::collection(App\Post::paginate());

Will return below result:

{
  "status": true,
  "http_code": 200,
  "message": "Success.",
  "data": [
    {
      "id": 1,
      "title": "First post",
      "slug": "first-post",
      "content": "This is the first post",
      "sort_order": 1,
      "created_at": "2020-04-21T13:40:45.000000Z",
      "updated_at": "2020-04-21T13:40:45.000000Z"
    },
    ...
  ],
  "meta": {
    "currenct_page": 1,
    "last_page": 3,
    "from": 1,
    "to": 25,
    "per_page": 25,
    "total": 60,
    "has_more_pages": true
  },
  "links": {
    "first": "http://your-app-url?page=1",
    "last": "http://your-app-url?page=3",
    "prev": null,
    "next": "http://your-app-url?page=2"
  }
}

Besides created and validationError, below shorthand methods are available for your convenience:

// return http 400 Bad request error.
return ApiResponse::badRequest('Optional message here'); 

// return http 401 Unauthorized error.
return ApiResponse::unauthorized(); 

// return http 403 Forbidden error.
return ApiResponse::forbidden(); 

// return http 404 Not found error.
return ApiResponse::notFound(); 

// return http 500 Internal server error.
return ApiResponse::internalServerError(); 

Tip: Pass a message to the method to put your own custom message.

Change log

Please see the changelog for more information on what has changed recently.

Credits

License

MIT. Please see the license file for more information.