mohamedahmed/api-response

Reusable trait for standardized API responses

v1.0.0 2025-07-12 20:58 UTC

This package is not auto-updated.

Last update: 2025-07-13 20:42:58 UTC


README

A reusable Laravel package for building consistent JSON API responses.
It helps you standardize your API outputs with data, pagination, exceptions, and error structures — cleanly and efficiently.

Package info

URL: https://packagist.org/packages/mohamedahmed/api-response

📦 Installation

composer require mohamedahmed/api-response

🚀 Usage

In your Laravel controller:

use MohamedAhmed\ApiResponse\Traits\ResponseApi;

class SomeController extends Controller
{
    use ResponseApi;

    public function index()
    {
        $this->setData(SomeModel::all());
        return $this->apiResponse();
    }
}

🧠 Available Methods

setData($data)

Sets the main response data.

If data is paginated, pagination details are auto-included.

$this->setData(User::all());
$this->setData(User::paginate(10));

setException(Throwable $exception)

Stores an exception and adds error info in the response.

try {
    // logic
} catch (\Exception $e) {
    $this->setException($e);
    $this->setCode(500);
    return $this->apiResponse();
}

setEc(int $code)

Sets an internal error code, useful for debugging and frontend error mapping.

$this->setEc(1001); // Internal reference code

setMessages(array|string $messages)

Custom messages for the user.

$this->setMessages(['Created successfully']);

setCode(int $httpCode)

Sets HTTP status code (defaults to 200).

$this->setCode(201); // HTTP Created

apiResponse()

Builds and returns the full JSON response.

return $this->apiResponse();

✅ Example Response

{
  "code": 200,
  "responseStatus": true,
  "messages": [],
  "response": {
    "dataLength": 3,
    "pagination": {
      "path": "/api/products?page=1",
      "total": 50,
      "perPage": 10,
      "currentPage": 1,
      "lastPage": 5
    },
    "data": [{}, {}, {}]
  },
  "error": {
    "errorCode": null,
    "line": null,
    "errorMessage": null,
    "file": null
  }
}