Reputation: 393
I'm pretty new to Symfony and API Platform. I'm trying to create a custom resource/operation which receives the body of the request, fetches data from the database according to the values and then returns a collection of the entity back to the client.
Example:
A GET
request with the following body:
{
"trackName": "example"
"anotherKey": "anotherValue"
}
According to these attributes I would like to query data, do calculations and then return the data.
I'm trying to figure out how to make this the API Platform way. I've been googling and looking for it in the documentation for hours, but I can't find a way to achieve this.
I've tried to query data with a CollectionDataProvider
and with a controller like this:
/**
* @ApiResource(
* itemOperations={
* "tracks_custom_endpoint"={
* "method"="GET",
* "path"="/tracks/custom_endpoint",
* "controller"=MyController::class,
* "read"=false
* }
* }
* )
* @ORM\Entity(repositoryClass=SpotifyTrackRepository::class)
*/
class Track
{
// Attributes, setters and getters
}
However, either way I can't access the body of the request respectively the JSON data which has been sent with it. Is there a way I can access this data somehow and then process it.
Upvotes: 0
Views: 3099
Reputation: 724
First of all, consider that itemOperations
specify endpoints that interact with a single resource. Whereas collectionOperations
specify endpoints that interact with the entire resource collection. Sounds like your endpoint should be configured under collectionOperations
as you are seeking to return a filtered resource collection, not a single resource.
Secondly, it is unusual for collection GET
operations to expect a request body payload in order to provide collection filters. These are more commonly provided using query parameters. API Platform ships with many query parameter filters out of the box that cover most use cases (yours included). Otherwise use Extensions for more custom and complex collection filtering.
Finally, there are Data Transformers that allow you to control how input (request payload) is transformed into resources, or how resources are transformed into output (response payload). This seems to be what you are looking for. However, I suggest considering my previous points before going down this path.
Upvotes: 1