Download the PHP package paysera/lib-api-bundle without Composer
On this page you can find all versions of the php package paysera/lib-api-bundle. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Informations about the package lib-api-bundle
PayseraApiBundle
Symfony bundle that allows easy configuration for your REST endpoints.
Why?
If you write quite many REST endpoints, some of the code or the structure itself gets repeated. If you want to add some functionality to all your endpoints, this could also get troublesome if you just wrote some custom code for each of them.
Difference from API Platform
API Platform gives lots of API specification options, documentation generation and such. This is available as it knows all the relations and fields in your objects. But for that, you need to configure the objects for all these features, including serialization options.
This approach is perfect for small applications but can be a pain on larger ones or the ones that need long term support and tend to change time to time.
When some custom functionality is needed, it's really easier to just implement it in code than to correctly configure it (if such configuration is even available).
This bundle gives a bit more control:
- each route is defined explicitly and has controller action that's executed. This allows to track the execution better and use any custom programming code when needed;
- for serialization/normalization code is used, not configuration. This makes it also more explicit and configurable. Tightly coupling REST interface with business model does not seem as a good idea for us.
It's a bit more boilerplate, but easily customisable when needed.
Installation
If you're not using symfony flex, add the following bundles to your kernel:
Configuration
Usage
Creating resource
To normalize and denormalize data from requests and to responses, PayseraNormalizationBundle is used. It works by writing a class for each of your resource. This makes it explicit and allows easy customization for mapping to/from your domain models (they usually are Doctrine entities).
Normalizer example:
In this case you'd also need to implement normalizer for Address
class.
It's easiest to configure REST endpoints using annotations/attributes. This requires your routing to be provided in controller annotations/attributes, too.
Controller example using annotations:
Controller example using attributes:
Don't forget to also import your controller (or Controller
directory) into routing configuration. For example:
This also requires that your controller's service ID would be the same as its FQCN.
HTTP example
Fetching resource
Controller example using annotations:
Controller example using attributes:
For path attributes PathAttributeResolverInterface
should be implemented, as in this
case we receive just a scalar type (ID), not an object.
By default, bundle tries to find resolver with type registered as fully qualified class name of that parameter in the type-hint.
You have at least few options to make this work.
- Making your own path attribute resolver. For example:
Tag service with paysera_api.path_attribute_resolver
, provide FQCN as type
attribute.
-
Reusing
DoctrinePathAttributeResolver
class to configure the needed service. For example: - Configuring supported classes and search fields in
config.yml
. This is practically the same as the previous option.
HTTP example
Fetching list of resources
Controller example using annotations:
Controller example using attributes:
Denormalizer for UserFilter
:
Code in UserRepository
:
As seen in this example, bundle integrates support for Paysera Pagination component.
In this case, actual database fetch is performed in the normalizer itself. This is done due to several reasons:
- to allow configuring total count strategy and maximum offset for the whole application (see below);
- to support optional total count and optional items. By default, if client does not explicitly ask for total count of resources, it's not calculated.
Configuration example:
Overriding options for specific actions:
Available strategies:
always
– total count is calculated by default, unless explicitly excluded from returned fields;optional
– total count is not calculated by default, but could, if explicitly included in returned fields;never
– total count is never calculated;default
– available only forPagedQuery
, falls back to globally configured strategy.
When you explicitly set always
strategy in ConfiguredQuery
object, maximum offset will be ignored. If you
still need it, configure it explicitly in ConfiguredQuery
, just like the strategy itself.
If you use some other strategy and configure maximum offset, there's currently no way to allow any offset for an endpoint explicitly.
Request and response structures
Pager is denormalized from the following query string fields:
limit
. Limits count of resources in a page. Defaults to configureddefault_limit
value;offset
. Skips some number of results. Should only be used to go to Nth page. Is restrained tomaximum_offset
value by default;after
. Accepts cursor from previous result to provide "next page" of results;before
. Accepts cursor from previous result to provide "previous page" or results;sort
. Accepts list of fields, configured byConfiguredQuery::addOrderingConfiguration
, separated by comma. To order descending, prefix specific item with-
. For example,?sort=-date_of_birth,registered_at
would result in something likeORDER BY date_of_birth DESC, registered_at ASC
.
Only one of ofset
/after
/before
can be provided.
Response structure has the following fields:
items
. Array of normalized resources;_metadata.total
. Integer, total count of resources. Missing by default, this depends on strategy andfields
parameter in query string;_metadata.has_next
. Boolean, whether next page is currently available;_metadata.has_previous
. Boolean, whether previous page is currently available;_metadata.cursors.after
. String, pass asafter
parameter in query string to get next page;_metadata.cursors.before
. String, pass asbefore
parameter in query string to get previous page.
Keep in mind that cursors could be missing in some rare cases (for example, no results at all). On another hand, they are provided even if there currently is no next/previous page. This could be used to check if any new resources were created – quite handy when used for synchronizing with backend.
Don't make any assumptions about internal structure of cursor value, as this could change with any release.
HTTP examples
To get only total count:
This will actually make only the SELECT
statement for the total count, no items will be selected.
To get page of resources with the total count:
To get the next page:
"2-abc"
is taken from _metadata.cursors.after
in this case.
Let's assume that resources are ordered by creation date in descending order. To get if any new resources were created:
In this case, if there would be zero results, _metadata.cursors.before
would still be the same. Saving last
cursor and iterating this way until we have "has_previous": false
is a reliable way to synchronize resources.
Annotations/Attributes reference
Body
Instructs to convert request body into an object and pass to the controller as an argument.
Option name | Default value | Description |
---|---|---|
parameterName |
Required | Specifies parameter name (without $ in controller action for passing denormalized data |
denormalizationType |
Guessed from parameter's type-hint | Denormalization type to use for body data denormalization |
optional |
true if parameter has default value |
Allows overwriting requirement for request body. Optional means that empty request body can be passed |
BodyContentType
Configuration for allowed request content types and whether body should be JSON-decoded before passing to denormalizer.
Option name | Default value | Description |
---|---|---|
supportedContentTypes |
Required | Array of supported Content-Type values. Can be * for any content type or something/* for validating only the first part. For example, this can be useful to allow only images |
jsonEncodedBody |
false |
Whether content should be JSON-decoded before passing to denormalizer |
If not configured, defaults to JSON-encoded body and 2 allowed Content-Type values: ""
(empty) and "application/json"
.
For this annotation/attribute to have any effect, Body
annotation/attribute must be present. Provide plain
as denormalizationType
if you want denormalization process to be skipped.
Validation
Configures or switches off validation for object, denormalized from request body. By default, validation is always enabled.
You can turn it off for an action or whole controller class.
If annotation/attribute is provided on both class and action, the one on action "wins" – they are not merged together.
Option name | Default value | Description |
---|---|---|
enabled |
true |
Allows to explicitly disable the validation |
groups |
['Default'] |
Validation groups to be used when validating. Empty list of groups is the same as disabled validation |
violationPathMap |
[] |
Associative array to convert propertyPath into REST fields. By default, camelCase is already converted to underscore_case. Use this if you have naming or structure mismatch |
ResponseNormalization
Configures normalization type to use for method's return value, if you'd need custom one.
By default, REST endpoints try to normalize any value returned from controller's action if it's not a Response
object.
If nothing is returned from the method (void
), empty response with HTTP status code 204
is provided.
Option name | Default value | Description |
---|---|---|
normalizationType |
Guessed from return value | Normalization type to use for normalizing method's return value |
PathAttribute
Configures denormalization for some concrete part of the path. Usually used to find entities by their IDs.
Multiple such annotations/attributes can be used in a single controller's action.
Option name | Default value | Description |
---|---|---|
parameterName |
Required | Specifies parameter name (without $ in controller action for passing denormalized data |
pathPartName |
Required | Specifies routing attribute to use for denormalization (for /users/{id} use id ) |
denormalizationType |
Guessed from type-hint + :find suffix |
Allows configuring custom denormalization type to use. Registered denormalizer must implement MixedTypeDenormalizerInterface |
resolutionMandatory |
true if parameter has no default value |
Specifies whether 404 error should be returned if parameter is not resolved |
Query
Instructs to convert query string into an object and pass to the controller as an argument.
Multiple annotations/attributes can be used to map several different objects.
Option name | Default value | Description |
---|---|---|
parameterName |
Required | Specifies parameter name (without $ in controller action for passing denormalized data |
denormalizationType |
Guessed from type-hint | Allows configuring custom denormalization type to use. Registered denormalizer must implement MixedTypeDenormalizerInterface |
validation |
Enabled with ['Default'] groups |
Use another @Validation annotation/attribute here, just like when configuring validation for request body |
RequiredPermissions
Instructs to check for permissions in security context for that specific action.
Could be also added in the class level. Permissions from class and method level annotations/attributes are merged together.
Option name | Default value | Description |
---|---|---|
permissions |
Required | List of permissions to be checked before any denormalization takes place |
Configuration without using annotations/attributes
It's also possible to configure options defining RestRequestOptions
as a service
and tagging it with paysera_api.request_options
.
Example:
Semantic versioning
This library follows semantic versioning.
See Symfony BC rules for basic information about what can be changed and what not in the API.
Please do not use any services not marked with public="true"
and any classes or methods marked with @internal
as these could change in any release.
Running tests
Contributing
Feel free to create issues and give pull requests.
You can fix any code style issues using this command:
All versions of lib-api-bundle with dependencies
ext-json Version *
symfony/framework-bundle Version ^3.4.34|^4.3|^5.4|^6.0
symfony/security-bundle Version ^3.4.34|^4.3|^5.4|^6.0
symfony/validator Version ^3.4.34|^4.3|^5.4|^6.0
paysera/lib-normalization-bundle Version ^1.1.0
paysera/lib-normalization Version ^1.2
paysera/lib-object-wrapper Version ~0.1
paysera/lib-pagination Version ^1.0
paysera/lib-dependency-injection Version ^1.3.0
psr/log Version ^1.0|^2.0
doctrine/persistence Version ^1.3.8 || ^2.0.1 || ^3.0
doctrine/annotations Version ^1.14 || ^2.0