diff --git a/symfony/controllers.md b/symfony/controllers.md index 276179e12f1..ef3677a52b9 100644 --- a/symfony/controllers.md +++ b/symfony/controllers.md @@ -395,6 +395,66 @@ See [Built-in Event Listeners](../core/events.md#built-in-event-listeners) for m In your custom controller, the `__invoke()` method parameter should be called the same as the entity identifier. So for the path `/user/{uuid}/bookmarks`, you must use `__invoke(string $uuid)`. +## Using the ApiOperation Attribute + +Since API Platform 5.1, the `#[ApiOperation]` attribute declares an API Platform operation directly +on a controller method. The path comes from the Symfony `#[Route]` of the method, so the +configuration lives in one place. This attribute is available for Symfony only. + +```php +reference, status: 'confirmed'); + } +} +``` + +API Platform deserializes and validates the request body into `CheckoutInput`, calls the controller +and serializes the returned `CheckoutOutput` according to the negotiated format. + +The operation accepts the usual options, including the flags `read`, `deserialize`, `validate`, +`security`, `serialize` and `write` that toggle the corresponding stages of the request pipeline. +For example, `new Post(..., security: 'is_granted("ROLE_USER")')` restricts the controller to +authenticated users. + +The attribute works with and without `use_symfony_listeners`. + +### Rules + +- Controllers must be tagged `controller.service_arguments`, which is the case with + `#[AsController]` or when extending `AbstractController`. API Platform scans them when the + container compiles. +- The resource class is the `class` option of the operation, or its `output` when `class` is not + set. Setting only `input` throws an exception. +- If this class is already a resource, the operation is added to its first `#[ApiResource]` and + inherits its configuration. Otherwise, the class becomes a resource. +- The route name is the `routeName` option of the operation, or the name of the `#[Route]` of the + method. The `methods` of the route must allow the HTTP method of the operation. If a class-level + `#[Route]` defines a `name`, it prefixes the method route name. +- `uriTemplate` is forbidden, the path is owned by the route. +- A request that matches the controller through a route other than the operation route throws an + exception. Set `routeName` on the operation to bind it to that route. +- A controller carrying `#[ApiOperation]` that cannot be bound to its operation throws an exception. +- `read` is disabled by default on `Get` and `GetCollection` operations: the controller returns the + data. On other operations with `uriVariables`, API Platform reads the resource through the + provider before calling the controller. Set `read: false` to skip it. + ## Alternative Method There is another way to create a custom operation. However, we do not encourage its use. Indeed,