Download the PHP package mediagone/symfony-easy-api without Composer
On this page you can find all versions of the php package mediagone/symfony-easy-api. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Informations about the package symfony-easy-api
Symfony EasyAPI
This package provides helper classes to build a Json API very easily from plain Symfony controllers. \ Supported features :
- Single and Collection results
- Pagination for Collection results
- Out of the box support for most useful status codes (200, 201, 202, 204, 400, 401, 403, 404, 405, 409, 410, 415, 422, 429, 500 and 501).
Installation
This package requires PHP 7.4+.
Add it as Composer dependency:
Introduction
This package provides several classes to handle API requests and return structured JSON responses:
ApiPayload200SuccessApiPayload201CreatedApiPayload202AcceptedApiPayload204NoContentApiPayloadError400BadRequestApiPayloadError401UnauthorizedApiPayloadError403ForbiddenApiPayloadError404NotFoundApiPayloadError405MethodNotAllowedApiPayloadError409ConflictApiPayloadError410GoneApiPayloadError415UnsupportedMediaTypeApiPayloadError422UnprocessableEntityApiPayloadError429TooManyRequestsApiPayloadError500ServerErrorApiPayloadError501NotImplemented
Examples
The easiest way to build an API controller is to use the EasyApi class and wrap the controller code in an anonymous function, to benefit from automatic error handling.
1. Entity instance API endpoint
The EasyApi->response method accepts any callable argument that returns an ApiPayload instance.
In case of success, the previous controller will return the following JSON object:
Or a "not found" response:
Or a "server error" response:
Note: errorCode is the internal error's code of the PHP exception (0 by default). You can generally define it by passing an additional integer argument to the constructor, eg. throw new LogicException("Invalid\$thingIdvalue ($thingId)", 1234);.
2. Entity collection API endpoint
You can also return multiple results by using the ApiPayload200Success::createWithArrayResult factory method:
It will result in a slightly different JSON object:
3. Collection pagination
When dealing with a lot of database entries, you may want to paginate results to retrieve them chunk by chunk. \
The package provides the ApiPagination class to help with that feature.
It requires two database queries: one to count the total number of results, and another to fetch the requested results:
Assuming that you have 93 rows in your database and you are requesting the 2nd page of 5 results, you'll receive the following JSON response:
License
Symfony EasyAPI is licensed under MIT license. See LICENSE file.
All versions of symfony-easy-api with dependencies
ext-json Version *
symfony/http-foundation Version ^4.0|^5.0|^6.0|^7.0