Skip to content

Commit 590f5c7

Browse files
bpolaszekdunglas
authored andcommitted
Custom serialization groups for custom operations (#588)
* Custom serialization groups for custom operations * Update operations.md
1 parent 60e3406 commit 590f5c7

File tree

1 file changed

+78
-0
lines changed

1 file changed

+78
-0
lines changed

core/operations.md

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -637,6 +637,84 @@ Or in XML:
637637
It is mandatory to set the `method`, `path` and `controller` attributes. They allow API platform to configure the routing path and
638638
the associated controller respectively.
639639

640+
#### Serialization Groups
641+
642+
You may want different serialization groups for your custom operations. Just configure the proper `normalization_context` and/or `denormalization_context`in your operation:
643+
644+
```php
645+
<?php
646+
// src/Entity/Book.php
647+
648+
use ApiPlatform\Core\Annotation\ApiResource;
649+
use App\Controller\BookSpecial;
650+
use Symfony\Component\Serializer\Annotation\Groups;
651+
652+
/**
653+
* @ApiResource(itemOperations={
654+
* "get",
655+
* "special"={
656+
* "path"="/books/{id}/special",
657+
* "controller"=BookSpecial::class,
658+
* "normalization_context"={"groups"={"special"}}
659+
* }
660+
* })
661+
*/
662+
class Book
663+
{
664+
//...
665+
666+
/**
667+
* @Groups("special")
668+
*/
669+
private $isbn;
670+
}
671+
```
672+
673+
Or in YAML:
674+
675+
```yaml
676+
# api/config/api_platform/resources.yaml
677+
App\Entity\Book:
678+
itemOperations:
679+
get: ~
680+
special:
681+
method: 'GET'
682+
path: '/books/{id}/special'
683+
controller: 'App\Controller\BookSpecial'
684+
normalization_context:
685+
groups: ['special']
686+
```
687+
688+
Or in XML:
689+
690+
```xml
691+
<?xml version="1.0" encoding="UTF-8" ?>
692+
<!-- api/config/api_platform/resources.xml -->
693+
694+
<resources xmlns="https://api-platform.com/schema/metadata"
695+
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
696+
xsi:schemaLocation="https://api-platform.com/schema/metadata
697+
https://api-platform.com/schema/metadata/metadata-2.0.xsd">
698+
<resource class="App\Entity\Book">
699+
<itemOperations>
700+
<itemOperation name="get" />
701+
<itemOperation name="special">
702+
<attribute name="method">GET</attribute>
703+
<attribute name="path">/books/{id}/special</attribute>
704+
<attribute name="controller">App\Controller\BookSpecial</attribute>
705+
<attribute name="normalization_context">
706+
<attribute name="groups">
707+
<group>special</group>
708+
</attribute>
709+
</attribute>
710+
</itemOperation>
711+
</itemOperations>
712+
</resource>
713+
</resources>
714+
```
715+
716+
#### Entity Retrieval
717+
640718
If you want to bypass the automatic retrieval of the entity in your custom operation, you can set the parameter
641719
`_api_receive` to `false` in the `default` attribute:
642720

0 commit comments

Comments
 (0)