Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/dees040/laravel-api-responses
Return readable API responses
https://github.com/dees040/laravel-api-responses
api laravel php response
Last synced: about 4 hours ago
JSON representation
Return readable API responses
- Host: GitHub
- URL: https://github.com/dees040/laravel-api-responses
- Owner: dees040
- Created: 2017-08-01T12:53:51.000Z (over 7 years ago)
- Default Branch: master
- Last Pushed: 2023-02-24T16:25:54.000Z (over 1 year ago)
- Last Synced: 2024-04-02T22:21:54.494Z (7 months ago)
- Topics: api, laravel, php, response
- Language: PHP
- Homepage:
- Size: 18.6 KB
- Stars: 67
- Watchers: 5
- Forks: 5
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Laravel API Responses
A very small package which helps you to easily returning readable API responses.
## Installation
Install the package via Composer.
```bash
composer require dees040/laravel-api-responses
```You're ready to go!
## Usage
Just use one of the helper functions and you're good to go.
```php
isAdmin()) {
return forbidden();
}
return ok($user);
}
}
```## Methods
All methods accept a `$data` parameter. This can be any data which can be used in a JSON response, such as strings, integers, arrays, models, etc..
| Method | Status Code |
| ----------------------------------------- |:-------------:|
| `ok($data)` | 200 |
| `created($data)` | 201 |
| `accepted($data)` | 202 |
| `no_content()` | 204 |
| `bad_request($message, $errors)` | 400 |
| `unauthenticated($message, $errors)` | 401 |
| `forbidden($message, $errors)` | 403 |
| `not_found($message, $errors)` | 404 |
| `method_not_allowed($message, $errors)` | 405 |
| `not_acceptable($message, $errors)` | 406 |
| `teapot($message, $errors)` | 418 |
| `unprocessable_entity($message, $errors)` | 422 |### Custom response (code)
If you'd wish to send a status code which is not in the list you could use the `json_response($data = null, $status = 200)` helper function. [Here](https://www.cheatography.com/kstep/cheat-sheets/http-status-codes/) you can find a cheat sheet for HTTP status codes or use my personal favorite [http.cat](https://http.cat) 😉.
If you want to send error response you can use the `error_json_response($message = '', $errors = [], $status = 400)`. This method will send an json response like this:
```php
error_json_response('User not found.', [
'id' => 'The ID does not exists.'
]);
```Output:
```json
{
"message": "User not found.",
"errors": {
"id": "The ID does not exists."
}
}
```