{"id":15027128,"url":"https://github.com/kennedy-osaze/laravel-api-response","last_synced_at":"2025-08-21T11:33:44.142Z","repository":{"id":39987744,"uuid":"484256946","full_name":"kennedy-osaze/laravel-api-response","owner":"kennedy-osaze","description":"Renders consistent HTTP JSON responses for API-based projects","archived":false,"fork":false,"pushed_at":"2023-07-03T16:03:09.000Z","size":63,"stargazers_count":65,"open_issues_count":2,"forks_count":6,"subscribers_count":2,"default_branch":"main","last_synced_at":"2024-12-07T11:12:47.320Z","etag":null,"topics":["api","json","laravel","php-8","response"],"latest_commit_sha":null,"homepage":"","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/kennedy-osaze.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2022-04-22T01:29:36.000Z","updated_at":"2024-09-13T18:40:53.000Z","dependencies_parsed_at":"2023-02-18T16:01:24.656Z","dependency_job_id":null,"html_url":"https://github.com/kennedy-osaze/laravel-api-response","commit_stats":null,"previous_names":[],"tags_count":6,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kennedy-osaze%2Flaravel-api-response","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kennedy-osaze%2Flaravel-api-response/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kennedy-osaze%2Flaravel-api-response/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kennedy-osaze%2Flaravel-api-response/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/kennedy-osaze","download_url":"https://codeload.github.com/kennedy-osaze/laravel-api-response/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":230511479,"owners_count":18237657,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["api","json","laravel","php-8","response"],"created_at":"2024-09-24T20:05:49.297Z","updated_at":"2024-12-19T23:14:21.170Z","avatar_url":"https://github.com/kennedy-osaze.png","language":"PHP","funding_links":[],"categories":[],"sub_categories":[],"readme":"![Laravel API Response Logo](https://banners.beyondco.de/Laravel%20API%20Response.png?theme=dark\u0026packageManager=composer+require\u0026packageName=kennedy-osaze%2Flaravel-api-response\u0026pattern=architect\u0026style=style_1\u0026description=Renders+consistent+HTTP+JSON+responses+for+API-based+projects\u0026md=1\u0026showWatermark=0\u0026fontSize=100px\u0026images=https%3A%2F%2Flaravel.com%2Fimg%2Flogomark.min.svg)\n\n[![GitHub Workflow Status](https://img.shields.io/github/workflow/status/kennedy-osaze/laravel-api-response/tests?label=CI)](https://github.com/kennedy-osaze/laravel-api-response/actions?query=workflow%3ACI+branch%3Amain)\n[![Latest Version on Packagist](https://img.shields.io/packagist/v/kennedy-osaze/laravel-api-response.svg?style=flat-square)](https://packagist.org/packages/kennedy-osaze/laravel-api-response)\n[![License](https://img.shields.io/badge/license-MIT-brightgreen.svg)](LICENSE.md)\n[![Total Downloads](https://img.shields.io/packagist/dt/kennedy-osaze/laravel-api-response)](https://packagist.org/packages/kennedy-osaze/laravel-api-response)\n\n\u003c!--delete--\u003e\n\n****\n\nLaravel API Response is a package that helps to provide and render a consistent HTTP JSON responses to API calls as well as converting and formatting exceptions to JSON responses.\n\n## Version Compatibility\n\n Laravel  | Laravel API Response\n:---------|:----------------------\n 9.x      | 1.x\n 10.x     | 2.x\n\n## Installation\n\nYou can install the package via composer:\n\n```bash\ncomposer require kennedy-osaze/laravel-api-response\n```\n\nYou can publish the translation files using:\n\n```bash\nphp artisan vendor:publish --tag=\"api-response-translations\"\n```\n\nThis will create a vendor folder (if it doesn't exists) in the `lang` folder of your project and inside, a `api-response/en` folder that has two files: `errors.php` and `success.php`. Both files are used for the translation of message strings in the JSON response sent out.\n\nOptionally, you can publish the config file using:\n\n```bash\nphp artisan vendor:publish --tag=\"api-response-config\"\n```\n\n## Usage\n\n### Using Package Traits\n\nThis package provides two traits that can be imported into your projects; namely:\n\n- The `\\KennedyOsaze\\LaravelApiResponse\\Concerns\\RendersApiResponse` trait which can be imported into your (base) controller class, middleware class or even your exception handler class\n- The `\\KennedyOsaze\\LaravelApiResponse\\Concerns\\ConvertsExceptionToApiResponse` trait which should only be imported into your exception handler class.\n\nSo we can have on the base controller class (from which all other controller may extend from):\n\n```php\n\u003c?php\n\nnamespace App\\Http\\Controllers;\n\nuse Illuminate\\Foundation\\Auth\\Access\\AuthorizesRequests;\nuse Illuminate\\Foundation\\Bus\\DispatchesJobs;\nuse Illuminate\\Foundation\\Validation\\ValidatesRequests;\nuse Illuminate\\Routing\\Controller as BaseController;\nuse KennedyOsaze\\LaravelApiResponse\\Concerns\\RendersApiResponse;\n\nclass Controller extends BaseController\n{\n    use AuthorizesRequests, DispatchesJobs, ValidatesRequests, RendersApiResponse;\n}\n```\n\nOr some random controller class:\n\n```php\n\u003c?php\n\nnamespace App\\Http\\Controllers;\n\nuse App\\Http\\Controllers\\Controller;\nuse KennedyOsaze\\LaravelApiResponse\\Concerns\\RendersApiResponse;\n\nclass RandomController extends Controller\n{\n    use RendersApiResponse;\n}\n```\n\nIn any case, you have access to a load of methods which you can call to render your data. This includes:\n\n```php\n// Successful Responses\nreturn $this-\u003eokResponse('This is a random message', $data = null, $headers = []);\nreturn $this-\u003ecreatedResponse('This is a random message', $data = null, $headers = []);\nreturn $this-\u003eacceptedResponse($message, $data, $headers);\nreturn $this-\u003enoContentResponse();\nreturn $this-\u003esuccessResponse($message, $data = null, $status = 200, $headers = []);\n\n// Successful Responses for \\Illuminate\\Http\\Resources\\Json\\JsonResource\nreturn $this-\u003eresourceResponse($jsonResource, $message, $status = 200, $headers = []);\nreturn $this-\u003eresourceCollectionResponse($resourceCollection, $message, $wrap = true, $status = 200, $headers = []);\n\n// Error Responses\nreturn $this-\u003eunauthenticatedResponse('Unauthenticated message');\nreturn $this-\u003ebadRequestResponse('Bad request error message', $error = null);\nreturn $this-\u003eforbiddenResponse($message);\nreturn $this-\u003enotFoundResponse($message);\nreturn $this-\u003eclientErrorResponse($message, $status = 400, $error = null, $headers = []);\nreturn $this-\u003eserverErrorResponse($message);\nreturn $this-\u003evalidationFailedResponse($validator, $request = null, $message = null);\n\n$messages = ['name' =\u003e 'Name is not valid'];\n$this-\u003ethrowValidationExceptionWhen($condition, $messages);\n```\n\nAlso to handle exceptions, converting them to API response by using the `\\KennedyOsaze\\LaravelApiResponse\\Concerns\\ConvertsExceptionToApiResponse` trait in your exception handler which provides the `renderApiResponse` public method and this can be used as follows:\n\n```php\n\u003c?php\n\nnamespace App\\Exceptions;\n\nuse App\\Traits\\HandleApiException;\nuse Illuminate\\Foundation\\Exceptions\\Handler as ExceptionHandler;\nuse KennedyOsaze\\LaravelApiResponse\\Concerns\\ConvertsExceptionToApiResponse;\nuse Throwable;\n\nclass Handler extends ExceptionHandler\n{\n    use ConvertsExceptionToApiResponse;\n\n    public function render($request, Throwable $e)\n    {\n        return $this-\u003erenderApiResponse($e, $request);\n    }\n}\n```\n\nYou could also use the `renderable` method of the handler class:\n\n```php\n\u003c?php\n\nnamespace App\\Exceptions;\n\nuse App\\Traits\\HandleApiException;\nuse Illuminate\\Foundation\\Exceptions\\Handler as ExceptionHandler;\nuse KennedyOsaze\\LaravelApiResponse\\Concerns\\ConvertsExceptionToApiResponse;\nuse Throwable;\n\nclass Handler extends ExceptionHandler\n{\n    use ConvertsExceptionToApiResponse;\n\n    public function register()\n    {\n        $this-\u003erenderable(function (Throwable $e, $request) {\n            return $this-\u003erenderApiResponse($e, $request);\n        });\n    }\n}\n```\n\n### Using Package Classes\n\nAt the core of the above methods, there is an underlying `ApiResponse` class being called that can also be used as follows:\n\n```php\nuse KennedyOsaze\\LaravelApiResponse\\ApiResponse;\n\n$response = new ApiResponse($status = 200, $message = 'Hello world', $data = ['age' =\u003e 20], $header = []);\n\nreturn $response-\u003emake();\n\n// Result\n{\n    \"success\": true,\n    \"message\": \"Hello world\",\n    \"data\": {\n        'age' =\u003e 20\n    }\n}\n\n// OR\nreturn ApiResponse::create(400, 'Error occurred');\n\n// Result\n{\n    \"success\": false,\n    \"message\": \"Error occurred\"\n}\n\n// We could also have\n$validator = Validator::make([], ['name' =\u003e 'required']);\nreturn ApiResponse::fromFailedValidation($validator);\n\n// Result\n{\n    \"success\": true,\n    \"message\": \"Validation Failed.\",\n    \"errors\": [\n        \"name\": {\n            \"message\": \"The name field is required\",\n            \"rejected_value\": null\n        }\n    ]\n}\n\n// Also\n\n$response = response()-\u003ejson(['hello' =\u003e 'world']);\n\nreturn ApiResponse::fromJsonResponse($response, $message = 'Hello');\n\n// Result\n{\n    \"success\": true,\n    \"message\": \"hello\"\n    \"data\": {\n        \"hello\": \"world\"\n    }\n}\n```\n\nIf you would like to change the format for validation errors, you may call the `registerValidationErrorFormatter` static method of the `ApiResponse` class in the boot method of your `App\\Providers\\AppServiceProvider` class or any other service provider you want. You can do something like this:\n\n```php\n\u003c?php\n\n// App\\Providers\\AppServiceProvider\n\nuse Illuminate\\Contracts\\Validation\\Validator;\nuse Illuminate\\Http\\Request;\nuse KennedyOsaze\\LaravelApiResponse\\ApiResponse;\n\npublic function boot()\n{\n    ApiResponse::registerValidationErrorFormatter(function (Validator $validator, Request $request) {\n        return [\n            'error_messages' =\u003e $validator-\u003eerrors()-\u003eall(),\n        ];\n    });\n}\n```\n\n### Response Data\n\nThe response data `$data` to be rendered for successful response can be any of the following type:\n\n- array e.g. `['name' =\u003e 'Dummy']`\n- standard object e.g. `new stdClass`\n- integer e.g. `1`\n- boolean e.g. `true`\n- any Model object, `instance of \\Illuminate\\Database\\Eloquent\\Model`\n- any Collection object, `instance of \\Illuminate\\Support\\Collection`\n- any JsonResource object, `instance of \\Illuminate\\Http\\Resources\\Json\\JsonResource`\n- any Jsonable object, `instance of \\Illuminate\\Contracts\\Support\\Jsonable`\n- any JsonSerializable object, `instance of \\JsonSerializable`\n- any Arrayable object, `instance of \\Illuminate\\Contracts\\Support\\Arrayable`\n\nAny of the above can be used stored as `$data` and used thus:\n\n```php\nuse \\KennedyOsaze\\LaravelApiResponse\\ApiResponse;\n\nApiResponse::create(200, 'A message', $data)\n```\n\nFor API Resources [JsonResources](https://laravel.com/docs/9.x/eloquent-resources \"JsonResources\") , you can create JSON responses by doing the following:\n\n```php\n\nuse App\\Models\\Book;\nuse App\\Http\\Resources\\BookResource;\nuse App\\Http\\Resources\\BookCollection;\nuse KennedyOsaze\\LaravelApiResponse\\ApiResponse;\n\n$resource = new BookResource(Book::find(1));\n\nreturn ApiResponse::fromJsonResponse($resource-\u003eresponse(), 'A book');\n\n// Also\n\n$collection = BookResource::collection(Book::all());\n\nreturn ApiResponse:::fromJsonResponse($collection-\u003eresponse(), 'List of books');\n\n// Also\n\n$collection = new BookCollection(Book::paginate());\n\nreturn ApiResponse::fromJsonResponse($collection-\u003eresponse, 'Paginated list of books')\n```\n\n### Response Messages\n\nThis package uses translation files to translate messages defined when creating responses. This packages, as described earlier, comes with two translation files: `success.php` and `errors.php`. The `success.php` contains translations for success response messages while `errors.php` contains that of error response messages.\n\nGiven that you have a `success.php` translation file as thus:\n\n```php\n\u003c?php\n\nreturn [\n    'Account Created' =\u003e 'User account created successfully',\n    'invoice_paid' =\u003e 'Invoice with number :invoice_number has been paid.',\n];\n\n```\n\nThe `ApiResponse` class would be able to translate messages as follows:\n\n```php\n\u003c?php\n\nuse KennedyOsaze\\LaravelApiResponse\\ApiResponse;\n\nreturn ApiResponse::create(200, 'Account Created');\n\n// Result\n{\n    \"success\": true,\n    \"message\": \"User account created successfully\"\n}\n\n// Also:\n\nreturn ApiResponse::create(200, 'invoice_paid:invoice_number=INV_12345');\n\n// OR\n\nreturn ApiResponse::create(200, 'invoice_paid', [\n    '_attributes' =\u003e ['invoice_number' =\u003e 'INV_12345']\n]);\n\n// Result\n{\n    \"success\": true,\n    \"message\": \"Invoice with number INV_12345 has been paid.\"\n}\n\n// Also:\n\nreturn ApiResponse::create(200, 'invoice_paid', [\n    '_attributes' =\u003e ['invoice_number' =\u003e 'INV_12345'],\n    'name' =\u003e 'Invoice for Mr Bean',\n    'amount' =\u003e 1000,\n    'number' =\u003e 'INV_12345'\n]);\n\n// Result\n{\n    \"success\": true,\n    \"message\": \"Invoice with number INV_12345 has been paid.\",\n    \"data\": {\n        \"name\": \"Invoice for Mr Bean\",\n        \"amount\": 1000,\n        \"number\": \"INV_12345\"\n    }\n}\n```\n\nThis is similar to how messages for error responses are translated except with the fact that the error messages are read from the `errors.php` translation file instead (or whatever you specify in the config file).\n\nAlso, for error messages, you can decide that error response should have error codes. You can provide error codes in your responses in a couple of ways:\n\n```php\n\u003c?php\n\nuse KennedyOsaze\\LaravelApiResponse\\ApiResponse;\n\nreturn ApiResponse::create(400, 'Error message comes here.', [\n    'error_code' =\u003e 'request_failed' // The error code here is \"request_failed\"\n]);\n\n// Result\n{\n    \"success\": false,\n    \"message\": \"Error message comes here.\",\n    \"error_code\": \"request_failed\"\n}\n\n```\n\nAlso, you can use the `errors.php` translation file to translate error codes. Given the below `errors.php` file:\n\n```php\n\nreturn [\n\n    'error_code' =\u003e [\n        'example_code' =\u003e 'Just a failed error message',\n\n        'error_code_name' =\u003e 'Example error message with status :status',\n    ],\n];\n```\n\nWe can have a response with error code as follows:\n\n```php\n\u003c?php\n\nuse KennedyOsaze\\LaravelApiResponse\\ApiResponse;\n\nreturn ApiResponse::create(400, 'error_code.example_code');\n\n// Result\n\n{\n    \"success\": false,\n    \"message\": \"Just a failed error message\",\n    \"error_code\": \"example_code\"\n}\n\n// Also\n\nreturn ApiResponse::create(400, 'error_code.error_code_name', [\n    '_attributes' =\u003e ['status' =\u003e 'FAILED']\n]);\n\n// OR\n\nreturn ApiResponse::create(400, 'error_code.error_code_name:status=FAILED');\n\n// Result\n\n{\n    \"success\": false,\n    \"message\": \"Example error message with status FAILED\",\n    \"error_code\": \"error_code_name\"\n}\n\n```\n\n## Testing\n\n```bash\ncomposer test\n```\n\n## Changelog\n\nPlease see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.\n\n## Contributing\n\nPlease see [CONTRIBUTING](CONTRIBUTING.md) for details.\n\n## Security Vulnerabilities\n\nIf you discover any security related issues, please email [me.osaze@gmail.com](mailto:me.osaze@gmail.com) instead of using the issue tracker.\n\n## Credits\n\n- [Kennedy Osaze](https://github.com/kennedy-osaze)\n- [All Contributors](../../contributors)\n\n## License\n\nThe MIT License (MIT). Please see [License File](LICENSE.md) for more information.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkennedy-osaze%2Flaravel-api-response","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fkennedy-osaze%2Flaravel-api-response","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkennedy-osaze%2Flaravel-api-response/lists"}