|
1 | | -[](https://packagist.org/packages/harrisonratcliffe/laravel-api-handler) |
2 | | -[](https://github.com/harrisonratcliffe/laravel-api-handler/actions?query=workflow%3Arun-tests+branch%3Amain) |
3 | | -[](https://packagist.org/packages/harrisonratcliffe/laravel-api-handler) |
4 | | - |
5 | | -?style=for-the-badge&logo=laravel) |
| 1 | +<p align="center"><h1 align="center">LARAVEL API HANDLER</h1></p> |
| 2 | +<p align="center"> |
| 3 | + <em><code>composer require harrisonratcliffe/laravel-api-handler</code></em> |
| 4 | +</p> |
| 5 | +<p align="center"> |
| 6 | + <img src="https://img.shields.io/github/license/harrisonratcliffe/laravel-api-handler?style=default&logo=opensourceinitiative&logoColor=white&color=0080ff" alt="license"> |
| 7 | + <img src="https://img.shields.io/github/last-commit/harrisonratcliffe/laravel-api-handler?style=default&logo=git&logoColor=white&color=0080ff" alt="last-commit"> |
| 8 | + <img src="https://img.shields.io/github/languages/top/harrisonratcliffe/laravel-api-handler?style=default&color=0080ff" alt="repo-top-language"> |
| 9 | + <img src="https://img.shields.io/github/languages/count/harrisonratcliffe/laravel-api-handler?style=default&color=0080ff" alt="repo-language-count"> |
| 10 | +</p> |
| 11 | +<p align="center"><!-- default option, no dependency badges. --> |
| 12 | +</p> |
| 13 | +<p align="center"> |
| 14 | + <!-- default option, no dependency badges. --> |
| 15 | +</p> |
| 16 | +<br> |
| 17 | + |
| 18 | +## 🔗 Table of Contents |
| 19 | + |
| 20 | +- [📍 Overview](#-overview) |
| 21 | +- [👾 Features](#-features) |
| 22 | +- [🚀 Getting Started](#-getting-started) |
| 23 | + - [☑️ Prerequisites](#-prerequisites) |
| 24 | + - [⚙️ Installation](#-installation) |
| 25 | + - [🤖 Usage](#🤖-usage) |
| 26 | +- [🧪 Testing](#🧪-testing) |
| 27 | +- [🔰 Contributing](#-contributing) |
| 28 | +- [🎗 License](#-license) |
| 29 | + |
| 30 | +[//]: # (- [🙌 Acknowledgments](#-acknowledgments)) |
| 31 | + |
| 32 | +--- |
| 33 | + |
| 34 | +## 📍 Overview |
| 35 | + |
| 36 | +A Laravel package to easily handle API responses and exceptions. |
| 37 | + |
| 38 | +--- |
| 39 | + |
| 40 | +## 👾 Features |
| 41 | + |
| 42 | +- 🌟 Return clean, consistent API responses |
| 43 | +- 🛡️ Handle API exceptions with standardized error responses |
| 44 | +- 🚀 Easy integration with Laravel 10 and 11 |
| 45 | + |
| 46 | +--- |
| 47 | +## 🚀 Getting Started |
| 48 | + |
| 49 | +### ☑️ Prerequisites |
| 50 | + |
| 51 | +Before getting started with Laravel API Handler, ensure your runtime environment meets the following requirements: |
| 52 | + |
| 53 | +- **Programming Language:** PHP |
| 54 | +- **Package Manager:** Composer |
| 55 | +- **Laravel Version:** 10.0 or 11.0 *(may work in older version)* |
| 56 | + |
| 57 | + |
| 58 | +### ⚙️ Installation |
| 59 | + |
| 60 | +Install laravel-api-handler using one of the following methods: |
| 61 | + |
| 62 | +**Build from source:** |
| 63 | + |
| 64 | +1. Install the package via Composer: |
| 65 | +```sh |
| 66 | +composer require harrisonratcliffe/laravel-api-handler |
| 67 | +``` |
| 68 | + |
| 69 | +2. Publish the config with: |
| 70 | +```sh |
| 71 | +php artisan vendor:publish --tag="laravelapihandler-config" |
| 72 | +``` |
| 73 | + |
| 74 | +## 🔧 Configuration Options |
| 75 | + |
| 76 | +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: |
| 77 | + |
| 78 | +### 🐞 Debug Mode |
| 79 | +```php |
| 80 | +'debug_mode' => config('app.debug', false), |
| 81 | +``` |
| 82 | +- **Purpose**: Controls whether detailed error information is exposed |
| 83 | +- **Default**: Inherits from Laravel's `app.debug` configuration |
| 84 | +- **Security Warning**: 🚨 **Only enable in development environments** |
| 85 | +- **Behavior**: |
| 86 | + - When `true`: Potentially exposes sensitive error details |
| 87 | + - When `false`: Provides generic, safe error messages |
| 88 | + |
| 89 | +### 📡 Default Success Response |
| 90 | +```php |
| 91 | +'success_response' => 'API request processed successfully', |
| 92 | +'success_status_code' => 200, |
| 93 | +``` |
| 94 | +- **Success Message**: Customizable default message for successful API requests |
| 95 | +- **Status Code**: Standard HTTP 200 OK response |
| 96 | +- **Customization**: Easily modify the default success message to match your application's tone |
| 97 | + |
| 98 | +### 🚧 Default Error Messages |
| 99 | +```php |
| 100 | +'http_not_found' => 'The resource or endpoint cannot be found', |
| 101 | +'unauthenticated' => 'You are not authenticated', |
| 102 | +'model_not_found' => 'Unable to locate the %s you requested', |
| 103 | +'unknown_error' => 'An unknown error occurred', |
| 104 | +``` |
| 105 | + |
| 106 | +#### Error Message Breakdown |
| 107 | +- **`http_not_found`**: Used when a requested endpoint doesn't exist |
| 108 | +- **`unauthenticated`**: Triggered for unauthorized access attempts |
| 109 | +- **`model_not_found`**: Dynamic message for missing database records |
| 110 | + - Uses a `%s` placeholder for the specific resource type |
| 111 | + - Example: "Unable to locate the User you requested" |
| 112 | +- **`unknown_error`**: Fallback message for unexpected errors |
| 113 | + |
| 114 | +### 🛠️ Customization Tips |
| 115 | +- Modify the config file located at `config/laravel-api-handler.php` |
| 116 | +- Tailor messages to match your application's voice |
| 117 | +- Keep error messages informative but not overly technical |
| 118 | +- Ensure messages are user-friendly and provide clear guidance |
| 119 | + |
| 120 | +### 🤖 Usage |
| 121 | + |
| 122 | +### Success Responses |
| 123 | + |
| 124 | +```php |
| 125 | +// In your controller |
| 126 | +use Harrisonratcliffe\LaravelApiHandler\Facades\LaravelApiHandler; |
| 127 | + |
| 128 | +public function index() |
| 129 | +{ |
| 130 | + $data = User::all(); |
| 131 | + return LaravelApiHandler::successResponse( |
| 132 | + 'Users retrieved successfully', |
| 133 | + $data |
| 134 | + ); |
| 135 | +} |
| 136 | +``` |
| 137 | + |
| 138 | +#### Example Success Response |
| 139 | +```json |
| 140 | +{ |
| 141 | + "status": "success", |
| 142 | + "message": "Users retrieved successfully", |
| 143 | + "data": [ |
| 144 | + {"id": 1, "name": "John Doe"}, |
| 145 | + {"id": 2, "name": "Jane Smith"} |
| 146 | + ] |
| 147 | +} |
| 148 | +``` |
| 149 | + |
| 150 | +### Error Responses |
| 151 | + |
| 152 | +```php |
| 153 | +public function store() |
| 154 | +{ |
| 155 | + return LaravelApiHandler::errorResponse( |
| 156 | + 'Resource creation failed', |
| 157 | + 422, |
| 158 | + 'https://docs.yourapi.com/errors/resource-creation' |
| 159 | + ); |
| 160 | +} |
| 161 | +``` |
| 162 | + |
| 163 | +#### Example Error Response |
| 164 | +```json |
| 165 | +{ |
| 166 | + "status": "error", |
| 167 | + "error": { |
| 168 | + "code": 422, |
| 169 | + "message": "Resource creation failed", |
| 170 | + "documentation": "https://docs.yourapi.com/errors/resource-creation" |
| 171 | + } |
| 172 | +} |
| 173 | +``` |
| 174 | + |
| 175 | +### Method Signatures |
| 176 | + |
| 177 | +### `successResponse()` |
| 178 | +- `$message` (optional): Custom success message |
| 179 | +- `$data` (optional): Response data |
| 180 | +- `$statusCode` (optional): HTTP status code (default: 200) |
| 181 | + |
| 182 | +### `errorResponse()` |
| 183 | +- `$message` (required): Error description |
| 184 | +- `$statusCode` (optional): HTTP error code (default: 400) |
| 185 | +- `$documentation` (optional): Error documentation link |
| 186 | +- `$debug` (optional): Additional debug information |
| 187 | + |
| 188 | +### API Exception Handler |
| 189 | + |
| 190 | +#### Laravel 11 |
| 191 | + |
| 192 | +To configure the API Exception Handler on Laravel 11, add the following configuration to your `boostrap/app.php` file: |
| 193 | +```php |
| 194 | +use Harrisonratcliffe\LaravelApiHandler\ApiExceptionHandler; |
| 195 | + |
| 196 | +->withExceptions(function (Exceptions $exceptions) { |
| 197 | + // your other code here |
| 198 | + $exceptions->render(function (Throwable $exception, $request) { |
| 199 | + if ($request->is('api/*')) { |
| 200 | + return app(ApiExceptionHandler::class)->renderApiException($exception); |
| 201 | + } |
| 202 | + |
| 203 | + return $this->render($request, $exception); |
| 204 | + }); |
| 205 | + }) |
| 206 | +``` |
| 207 | + |
| 208 | +#### Laravel 10 |
| 209 | + |
| 210 | +To configure the API Exception Handler on Laravel 10, add the following configuration inside your render method of your `app/Exceptions/Handler.php` file: |
| 211 | +```php |
| 212 | +use Harrisonratcliffe\LaravelApiHandler\ApiExceptionHandler; |
| 213 | + |
| 214 | +// your other code here |
| 215 | +public function render($request, Throwable $exception) |
| 216 | + { |
| 217 | + if ($request->is('api/*')) { |
| 218 | + return app(ApiExceptionHandler::class)->renderApiException($exception); |
| 219 | + } |
| 220 | + |
| 221 | + return parent::render($request, $exception); |
| 222 | + } |
| 223 | +``` |
| 224 | + |
| 225 | +## 🧪 Testing |
| 226 | +Run the test suite using the following command: |
| 227 | +**Using `composer`** [<img align="center" src="https://img.shields.io/badge/PHP-777BB4.svg?style={badge_style}&logo=php&logoColor=white" />](https://www.php.net/) |
| 228 | + |
| 229 | +```sh |
| 230 | +vendor/bin/pest |
| 231 | +``` |
| 232 | + |
| 233 | + |
| 234 | +[//]: # (---) |
| 235 | + |
| 236 | +[//]: # (## 📌 Project Roadmap) |
| 237 | + |
| 238 | +[//]: # () |
| 239 | +[//]: # (- [X] **`Task 1`**: <strike>Implement feature one.</strike>) |
| 240 | + |
| 241 | +[//]: # (- [ ] **`Task 2`**: Implement feature two.) |
| 242 | + |
| 243 | +[//]: # (- [ ] **`Task 3`**: Implement feature three.) |
| 244 | + |
| 245 | +[//]: # () |
| 246 | +[//]: # (---) |
| 247 | + |
| 248 | +## 🔰 Contributing |
| 249 | + |
| 250 | +Contributions are welcome! |
| 251 | + |
| 252 | +- **💬 [Join the Discussions](https://github.com/harrisonratcliffe/laravel-api-handler/discussions)**: Share your insights, provide feedback, or ask questions. |
| 253 | +- **🐛 [Report Issues](https://github.com/harrisonratcliffe/laravel-api-handler/issues)**: Submit bugs found or log feature requests for the `laravel-api-handler` project. |
| 254 | +- **💡 [Submit Pull Requests](https://github.com/harrisonratcliffe/laravel-api-handler/blob/main/CONTRIBUTING.md)**: Review open PRs, and submit your own PRs. |
| 255 | + |
| 256 | +<details closed> |
| 257 | +<summary>Contributing Guidelines</summary> |
| 258 | + |
| 259 | +1. **Fork the Repository**: Start by forking the project repository to your github account. |
| 260 | +2. **Clone Locally**: Clone the forked repository to your local machine using a git client. |
| 261 | + ```sh |
| 262 | + git clone https://github.com/harrisonratcliffe/laravel-api-handler |
| 263 | + ``` |
| 264 | +3. **Create a New Branch**: Always work on a new branch, giving it a descriptive name. |
| 265 | + ```sh |
| 266 | + git checkout -b new-feature-x |
| 267 | + ``` |
| 268 | +4. **Make Your Changes**: Develop and test your changes locally. |
| 269 | +5. **Commit Your Changes**: Commit with a clear message describing your updates. |
| 270 | + ```sh |
| 271 | + git commit -m 'Implemented new feature x.' |
| 272 | + ``` |
| 273 | +6. **Push to github**: Push the changes to your forked repository. |
| 274 | + ```sh |
| 275 | + git push origin new-feature-x |
| 276 | + ``` |
| 277 | +7. **Submit a Pull Request**: Create a PR against the original project repository. Clearly describe the changes and their motivations. |
| 278 | +8. **Review**: Once your PR is reviewed and approved, it will be merged into the main branch. Congratulations on your contribution! |
| 279 | +</details> |
| 280 | + |
| 281 | +<details closed> |
| 282 | +<summary>Contributor Graph</summary> |
| 283 | +<br> |
| 284 | +<p align="left"> |
| 285 | + <a href="https://github.com{/harrisonratcliffe/laravel-api-handler/}graphs/contributors"> |
| 286 | + <img src="https://contrib.rocks/image?repo=harrisonratcliffe/laravel-api-handler"> |
| 287 | + </a> |
| 288 | +</p> |
| 289 | +</details> |
| 290 | + |
| 291 | +--- |
| 292 | + |
| 293 | +## 🎗 License |
| 294 | + |
| 295 | +This project is protected under the [MIT](https://choosealicense.com/licenses/mit) License. For more details, refer to the [LICENSE](https://github.com/harrisonratcliffe/laravel-api-handler/blob/main/LICENSE) file. |
| 296 | + |
| 297 | +[//]: # (---) |
| 298 | + |
| 299 | +[//]: # (## 🙌 Acknowledgments) |
| 300 | + |
| 301 | +[//]: # () |
| 302 | +[//]: # (- List any resources, contributors, inspiration, etc. here.) |
| 303 | + |
| 304 | +[//]: # () |
| 305 | +[//]: # (---) |
0 commit comments