Reputation: 388
I have the following annotation written in my Entity RegistrationHashes
in API platform:
#[ORM\Entity()]
#[ORM\Table(name: "registration_hashes")]
#[ApiResource(
operations: [new Get(), new GetCollection()],
normalizationContext: ['groups' => ['read']],
security: 'is_granted("ROLE_USER")',
)]
#[ApiFilter(
filterClass: SearchFilter::class,
properties: [
'registrationId' => SearchFilterInterface::STRATEGY_START,
'hash' => SearchFilterInterface::STRATEGY_EXACT,
]
)]
When query /registration_hashes
I can search for the two properties registrationId
and hash
They match and this works. Except I dont want to return a collection, I just want either the one row or not found. How can I apply my SearchFilter to GET operation only?
Upvotes: 0
Views: 92
Reputation: 929
Get
operation is not made to do that and can't be use like you want to.
Get
operation always need an api identifier in order to retrieve an item based on it. registrationId
in your case.
If you want to search for items you will always need to use collection operations.
In your case, just call your getCollection
operation with the needed parameters.
Something like that :
/api/registration_hashes?registrationId=xxx&hash=xxx
If you combination of registration and hash is unique you will get only one result.
Also, Search Filter of api platform are made to work only on collection operations. Its intentional.
Update :
One way to do it is to do something like that :
new Get(
uriTemplate: "/users/{registrationId}/{hash}
provider: CustomProvider::class
)
And do your own logic inside CustomProvider.php
to get the object using
public function provide(Operation $operation, array $uriVariables = [], array $context = [])
{
$hash = $uriVariables['hash'];
$registrationId = $uriVariables['registrationId']
//You own logic to get it from database
}
Look at https://api-platform.com/docs/main/core/state-providers/ for deeper explanation about state provider
Upvotes: 1