I’m working with Api Platform, Symfony and Doctrine. I’m expecting a JSON of an object from my frontend, which is essential in procuring the data from my backend. Since GET
requests don’t/should not have a body, I believe a Post()
Operation is the best way to achieve my goal. I have added an attribute to my entity, which resembles the following:
#[ORMEntity(repositoryClass: EntityRepository::class)]
#[ApiResource(
operations: [
new Get(security: "is_granted('ROLE_ADMIN') or is_granted('ROLE_USER')"),
new Post(
input: InputDto::class,
provider: StateProvider::class,
output: OutputDto::class,
uriTemplate: 'entity/{variable}',
uriVariables: ['variable' => 'variable'],
)
]
)]
My state provider resembles the following example:
class StateProvider implements ProviderInterface
{
public function __construct(
private RequestStack $requestStack
)
{
$this->requestStack = $requestStack;
}
public function provide(Operation $operation, array $uriVariables = [], array $context = []): object|array|null
{
$variable = $uriVariables['variable'] ?? null;
// logic
$outputDto = new OutputDto($dataProcuredFromLogic);
return $outputDto;
}
}
The logic seems to work just fine. If I add print_r($outputDto);
just before the return statement, I get exactly the data I expected. But when executing the request, the response is just the exact same InputDto
which I have sent through the body of the request, not the returned $outputDto
of the provider.
This makes me wonder if what I’ve hoped to achieve is even possible.
I have tried to use a state processor instead of a provider and using the exact same logic. The only differences being that I did not need a RequestStack
to get the input data, with it being in the parameters of the process()
Method and me having to change the return type of the process()
Method to my OutputDto
. What I have gotten there was an error that looked like this:
"[Semantical Error] line 0, col 75 near 'property = :property_p1': Error: Class App\Entity\Entity has no field or association named property"
I am guessing in has something to do with Doctrine, because of ":property_p1"
resembling what would seem like a parameter that was set on a QueryBuilder
, but as I said, the logic, including my DQL Queries, seemed to work just fine when I printed my results using print_r()
.
I’m not sure if I should use a controller as I have read that they are discouraged in the Api Platform documentation.
Could you help me return the actual wanted output?
Thank you in advance for any help you can provide!