Since you only need to describe the structure of the data to expose, API Platform is both a “design-first” and “code-first” API framework. However, the “design-first” methodology is strongly recommended: first you design the public shape of API endpoints.
To do so, you have to write a plain old PHP object (POPO) representing the input and output of your endpoint. This is the class
that is marked with the #[ApiResource]
attribute.
This class doesn’t have to be mapped with Doctrine ORM, or any other persistence system. It must be simple (it’s usually
just a data structure with no or minimal behaviors) and will be automatically converted to Hydra,
OpenAPI and GraphQL documentations or schemas by API Platform (there is a 1-1 mapping
between this class and those docs).
Then, it’s up to the developer to feed API Platform with an hydrated instance of this API resource object by implementing
the DataProviderInterface
. Basically, the data provider will query the persistence system (RDBMS,
document or graph DB, external API…), and must hydrate and return the POPO that has been designed as mentioned above.
When updating a state (POST
, PUT
, PATCH
, DELETE
HTTP methods), it’s up to the developer to properly persist the
data provided by API Platform’s resource object hydrated by the serializer.
To do so, there is another interface to implement: DataPersisterInterface
.
This class will read the API resource object (the one marked with #[ApiResource]
) and:
The logic of data persisters is the responsibility of application developers, and is out of the API Platform’s scope.
For Rapid Application Development, convenience and prototyping,
if and only if the class marked with #[ApiResource]
is also a Doctrine entity, the developer can use the Doctrine
ORM’s data provider and persister implementations shipped with API Platform.
In this case, the public (#[ApiResource]
) and internal (Doctrine entity) data models are shared. Then, API Platform will
be able to query, filter, paginate and persist data automatically.
This approach is super-convenient and efficient, but is probably not a good idea for non-CRUD
and/or large systems.
Again, it’s up to the developers to use, or to not use these built-in data providers/persisters depending on the business logic
they are dealing with.
API Platform makes it easy to create custom data providers and persisters.
It also makes it easy to implement patterns such as CQS
or CQRS thanks to the Messenger Component integration and the DTO support.
Last but not least, to create Event Sourcing-based systems, a convenient approach is:
#[ApiResource]
You can then benefit from the built-in Doctrine filters, sorting, pagination, auto-joins and all of the extension points provided by API Platform.
Made with love by
Les-Tilleuls.coop can help you design and develop your APIs and web projects, and train your teams in API Platform, Symfony, Next.js, Kubernetes and a wide range of other technologies.
Learn more