Package Data | |
---|---|
Maintainer Username: | nbourguig |
Maintainer Contact: | nbourguig@gmail.com (Nassif Bourguig) |
Package Create Date: | 2016-10-07 |
Package Last Update: | 2021-08-10 |
Home Page: | |
Language: | PHP |
License: | MIT |
Last Refreshed: | 2024-11-19 03:18:22 |
Package Statistics | |
---|---|
Total Downloads: | 12,836 |
Monthly Downloads: | 21 |
Daily Downloads: | 1 |
Total Stars: | 4 |
Total Watchers: | 4 |
Total Forks: | 0 |
Total Open Issues: | 8 |
A simple way to return well formatted json responses in a Laravel application.
You can install the package using composer
$ composer require tequilarapido/api-response
Add the service provider
Tequilarapido\ApiResponse\ApiResponseServiceProvider::class
This package comes with a helper function api_response()
, as sugar syntax to using app(Tequilarapido\ApiResponse\ApiResponse::class)
return api_response()->item(['result`' => 'success'])
Result :
{
"data":
{
"result":
"success"
}
}
return api_response()->item(collect(['Apple', 'Orange', 'Kiwi']))
Result :
{
"data":
{
"Apple",
"Orange",
"Kiwi",
}
}
return api_response()->item(collect(['Apple', 'Orange', 'Kiwi']))
Result :
{
"data": [1, 2, 3],
"meta": {
"pagination": {
"count": 3,
"current_page": 1,
"links": {
"next": "/?page=2"
},
"per_page": 3,
"total": 15,
"total_pages": 5
}
}
}
You can use transformers along with item()
, collection()
, and paginatedCollection
methods to transform results
before returning the responses.
To learn more about the concept behind transformers, please read the League\Fractal documentation.
Put in a simple way, a Transformer class
- must extends League\Fractal\TransformerAbstract
- and contains a method transform()
that take the raw value/object as an argument and transform it the way we want.
Let's assume that we need to return an api response containing a collection of books retreived from database, and we want to format/enhance/restrict results.
class BookTransformer extends TransformerAbstract
{
public function transform($book)
{
return [
'id' => (int)$book->id,
'title' => strtoupper($book->title),
'price' => '$' . $book->price,
'published_at' => $book->published_at->format('d/m/Y'),
'url' => 'https://store.books.com/books/' . $book->id
];
}
}
Route::get('/books', function () {
// ie. Book::all()
$books = collect([
(object)['title' => 'An awesome book', 'id' => '1', 'price' => 10, 'published_at' => Carbon::createFromFormat('Y-m-d', '2016-10-01')],
(object)['title' => 'A second awesome book', 'id' => '2', 'price' => 100, 'published_at' => Carbon::createFromFormat('Y-m-d', '2016-10-02')],
]);
return api_response()->collection($books, new BookTransformer);
});
Result:
{
"data": [
{
"id": 1,
"price": "$10",
"published_at": "01/10/2016",
"title": "AN AWESOME BOOK",
"url": "https://store.books.com/books/1"
},
{
"id": 2,
"price": "$100",
"published_at": "02/10/2016",
"title": "A SECOND AWESOME BOOK",
"url": "https://store.books.com/books/2"
}
]
}
For item()
, collection()
, and paginatedCollection
methods the returned result is a built Illuminate\Http\Response
object.
To be able to attach cookies you need to instruct api_response()
methods to not build the response by setting the $built argument to false, attach the cookie
and then build the response.
return api_response()
->item(['result`' => 'success'], null, null, false)
->withCookie(new \Symfony\Component\HttpFoundation\Cookie('name', 'value'))
->build();
For item()
, collection()
, and paginatedCollection
methods the returned result is a built Illuminate\Http\Response
object.
To be able to attach headers you need to instruct api_response()
methods to not build the response by setting the $built argument to false, attach the header
and then build the response.
return api_response()
->item(['result`' => 'success'], null, null, false)
->withHeader('X-CUSTOM', 'customvalue')
->build();
| Method | Usage |
|-------------|--------------|
| api_response()->noContent()
| Return an empty response with 204 No Content header.|
| api_response()->errorNotFound()
| Return a 404 Not found.|
| api_response()->errorBadRequest()
| Return a 404 Bad Request.|
| api_response()->errorForbidden()
| Return a 403 Forbidden.|
| api_response()->errorUnAUthorized()
| Return a 401 Unauthorized.|
| api_response()->errorInternal()
| Return a 500 Internal Error.|
| api_response()->error()
| Return a more customizable error (Accept MessageBag instance, staus code ...)|
Please see CHANGELOG for more information what has changed recently.
$ composer test
If you discover any security related issues, please email :author_email instead of using the issue tracker.
Please see CONTRIBUTING for details.
The MIT License (MIT). Please see License File for more information.