Search code examples
phpsymfonyapi-platform.comjson-ld

Extend ApiPlatforms GetCollection operation JsonLd response with additional data


Symfony 6, Api-Platform 3, Php 8

I have Symfony-Doctrine entity that I've annotated with Api-Platform's ApiResource annotation, and I am using the GetCollection operation, which does what it is designed to.

Let's say this entity is a model that stores fiat Transactions. The main fields for this example are amount (float) and date (datetime).

In the user interface, there is paginated table of these Transactions, which works great with all that Api-Platform has to offer.

I have a requirement that when a certain range of dates has been set, the list of transactions should show additional info: in this example the sum total of all the transactions for the queried period. I am using the Api-Platform's built-in filters.

My question is: Has anyone found a way to extend the Api-Platform's GetCollection JsonLd response with additional data? I have achieved this user interface functionality with a separate and specified API endpoint, that returns just the total for the submitted filters (range of dates), but I would prefer to unite these two API endpoints.

I have played around with Api-Platform's DataProviders and Dtos with no success.

I was trying to find the place where ApiPlatforms DataProvider is building the Doctrine DQL Query. My idea was to make a clone of it, modify it (keeping the set-up filters WHERE statements) and adding the result aside the JsonLD collection and pagination data.


Solution

  • There are several ways to do what you might want. The ideal solution depends on your exact requirements.

    for example

    • decorate the json ld normalizer to add arbitrary data to the response
    • decorate hydra normalizer to add response metadata
    • add an event subscriber to add additional data to your model
    • redesign your API resources, e.g. use subresources and serializer groups for embedding associations
    • create a doctrine query extension
    • create a custom action (not really recommended)
    • etc.

    several other options exist depending on your exact needs. There are lots of examples for almost any usecase https://api-platform.com/docs/core/