harrisonratcliffe / laravel-api-responses
A Laravel package to easily handle API responses and exceptions
Requires
- php: >=7.0
- illuminate/support: >=7.0
- spatie/laravel-package-tools: ^1.14
Requires (Dev)
- laravel/pint: ^1.0
- nunomaduro/collision: ^7.0
- nunomaduro/larastan: ^2.0
- orchestra/testbench: ^8.0
- pestphp/pest: ^2.0
- pestphp/pest-plugin-arch: ^2.0
- pestphp/pest-plugin-laravel: ^2.0
- phpunit/phpunit: ^10.0
- rector/rector: ^1.2
README
LARAVEL API RESPONSES
composer require harrisonratcliffe/laravel-api-responses
๐ Table of Contents
- ๐ Overview
- ๐พ Features
- ๐ Getting Started
- โ๏ธ Prerequisites
- โ Installation
- ๐ค Usage
- ๐งช Testing
- ๐ฐ Contributing
- ๐ License
๐ Overview
A Laravel package to easily handle API responses and exceptions.
๐พ Features
- ๐ Return clean, consistent API responses
- ๐ก๏ธ Handle API exceptions with standardized error responses
- ๐ Easy integration with Laravel 7 to 12
๐ Getting Started
โ๏ธ Prerequisites
Before getting started with Laravel API Responses, ensure your runtime environment meets the following requirements:
- Programming Language: PHP
- Package Manager: Composer
- Laravel Version: 7 or later
โ๏ธ Installation
Install laravel-api-responses using the following method:
- Install the package via Composer:
composer require harrisonratcliffe/laravel-api-responses
- Publish the config with:
php artisan vendor:publish --tag="apiresponses-config"
API Exception Handler
Note: if you use a different API route path than /api you should adjust the below if statement.
Laravel 11-12
To configure the API Exception Handler on Laravel 11-12, add the following configuration to your boostrap/app.php
file:
use Harrisonratcliffe\LaravelApiResponses\ApiExceptionHandler; ->withExceptions(function (Exceptions $exceptions) { // your other code here $exceptions->render(function (Throwable $exception, $request) { if ($request->expectsJson() || $request->is('api/*')) { return app(ApiExceptionHandler::class)->renderApiException($exception); } }); // your other code here })
Laravel 7-10
To configure the API Exception Handler on Laravel 7-10, add the following configuration inside your render method of your app/Exceptions/Handler.php
file:
use Harrisonratcliffe\LaravelApiResponses\ApiExceptionHandler; public function render($request, Throwable $exception) { // your other code here if ($request->expectsJson() || $request->is('api/*')) { return app(ApiExceptionHandler::class)->renderApiException($exception); } // your other code here }
Here's the modified README to reflect the new option for handling internal server error messages:
๐ง Configuration Options
The Laravel API Handler package provides a flexible configuration file that allows you to customize default response messages and behaviors. Let's break down each configuration option:
๐ Debug Mode
'debug_mode' => end('APP_ENV', false),
- Purpose: Controls whether detailed error information is exposed
- Default: Inherits from Laravel's
APP_ENV
environment variable - Security Warning: ๐จ Only enable in development environments
- Behavior:
- When
true
: Potentially exposes sensitive error details - When
false
: Provides generic, safe error messages
- When
๐ก Default Success Response
'success_response' => 'API request processed successfully.', 'success_status_code' => 200,
- Success Message: Customizable default message for successful API requests
- Status Code: Standard HTTP 200 OK response
- Customization: Easily modify the default success message to match your application's tone
๐ง Default Error Messages
'http_not_found' => 'The requested resource or endpoint could not be located.', 'unauthenticated' => 'You must be logged in to access this resource. Please provide valid credentials.', 'model_not_found' => 'The requested resource could not be found. This resource doesn\'t exist.', 'unknown_error' => 'An unexpected error has occurred. Please try again later or contact support if the issue persists.',
Error Message Breakdown
http_not_found
: Used when a requested endpoint doesn't existunauthenticated
: Triggered for unauthorized access attemptsmodel_not_found
: Dynamic message for missing database records- Provides clarity on what was not found
unknown_error
: Fallback message for unexpected errors
โ ๏ธ Internal Server Error Message
'show_500_error_message' => true,
- Purpose: Controls whether the actual error message from a 500/internal server error is returned.
- Default:
true
(actual error message will be shown) - Behavior:
- When
true
: The detailed error message is returned, which can aid in debugging. - When
false
: Theunknown_error
response will be used instead, maintaining user-friendliness.
- When
๐ ๏ธ Customization Tips
- Modify the config file located at
config/api-responses.php
- Tailor messages to match your application's voice
- Keep error messages informative but not overly technical
- Ensure messages are user-friendly and provide clear guidance
๐ค Usage
Success Responses
// In your controller use Harrisonratcliffe\LaravelApiResponses\Facades\ApiResponses; public function index() { $data = User::all(); return ApiResponses::success( 'Users retrieved successfully', $data ); }
Example Success Response
{ "status": "success", "message": "Users retrieved successfully", "data": [ {"id": 1, "name": "John Doe"}, {"id": 2, "name": "Jane Smith"} ] }
Error Responses
use Harrisonratcliffe\LaravelApiResponses\Facades\ApiResponses; public function store() { return ApiResponses::error( 'This virtual machine does not exist', 404, [ 'vm_id' => 12345 ], 'https://docs.yourapi.com/errors/some-error' ); }
Example Error Response
{ "status": "error", "message": "This virtual machine does not exist", "details": { "vm_id": 12345 }, "documentation": "https://docs.yourapi.com/errors/some-error" }
Method Signatures
successResponse()
$message
(optional): Custom success message$data
(optional): Response data$statusCode
(optional): HTTP status code (default: 200)
errorResponse()
$message
(required): Error description$statusCode
(optional): HTTP error code (default: 400)$details
(optional) Error details$documentation
(optional): Error documentation link$debug
(optional): Additional debug information
๐งช Testing
Run the test suite using the following command:
Using composer
ย
vendor/bin/pest
๐ฐ Contributing
Contributions are welcome!
- ๐ Report Issues: Submit bugs found or log feature requests for the
laravel-api-responses
project. - ๐ก Submit Pull Requests: Review open PRs, and submit your own PRs.
Contributing Guidelines
- Fork the Repository: Start by forking the project repository to your github account.
- Clone Locally: Clone the forked repository to your local machine using a git client.
git clone https://github.com/harrisonratcliffe/laravel-api-responses
- Create a New Branch: Always work on a new branch, giving it a descriptive name.
git checkout -b new-feature-x
- Make Your Changes: Develop and test your changes locally.
- Commit Your Changes: Commit with a clear message describing your updates.
git commit -m 'Implemented new feature x.'
- Push to github: Push the changes to your forked repository.
git push origin new-feature-x
- Submit a Pull Request: Create a PR against the original project repository. Clearly describe the changes and their motivations.
- Review: Once your PR is reviewed and approved, it will be merged into the main branch. Congratulations on your contribution!
๐ License
This project is protected under the MIT License. For more details, refer to the LICENSE file.