0

Using SF4 & Api platform : I would like to have a route for performing a random computation, and returning result to the client.. this seems to be simple
However I am not able to do it easily with custom operations

Here it is what I have done

I have my entity, for request & reponse, using normalization to have field only in request, and not in response
And I have my Controller with my custom operation + the corresponding route only for collection (as I don't have any id) in yaml in the api_platform/resources.yaml file
The controller is taking the entity in input and responding with it, hydrated by the result

I am getting the error :

2018-08-18T16:22:42+02:00 [critical] Uncaught PHP Exception ApiPlatform\Core\Exception\InvalidArgumentException: "Unable to generate an IRI for the item of type "App\Entity\Computation"" at /dev/git/app-api/vendor/api-platform/core/src/Bridge/Symfony/Routing/IriConverter.php line 127

But I think this is when the server is serializing the reponse, as the computation is performed (log inside are printed)

Entity\Computation.php :

class Computation
{
/**
 * @var double  you input
 *
 * @Assert\NotBlank
 * @Groups({"read","write"})
 */
public $input;

/**
 * @var double the result
 *
 * @Groups({"read"})
 */
public $result;
}

Controller\ComputationController.php :

class ComputationController
{
    private $service;

    public function __construct(MyService $service)
    {
        $this->service= $service;
    }

    public function __invoke(Position $data): Response
    {
        $this->service->compute($data);
        return $data;
    }
}

api_platform/resources.yaml :

resources:
  App\Entity\Computation:
    itemOperations: {}
    collectionOperations:
      compute:
        method: 'POST'
        path: '/compute'
        controller: 'App\Controller\ComputationController'
    attributes:
      normalization_context:
        groups: ['read']
      denormalization_context:
        groups: ['write']

Can someone help me with it ?
Thanks !

2 Answers 2

3

I found a solution, custom operation is totally not the way to do this..

In documentation of custom operation, it states:

Note: the event system should be preferred over custom controllers when applicable.

So the correct way to do simple, not related to an entity, operation is the usage of a Data Transfer Object (DTO)

Sign up to request clarification or add additional context in comments.

Comments

0

You dont have "get" item operation, which is mandatory. This is why Apip cant generate iri for you.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.