Skip to content

Commit c557656

Browse files
authored
Merge pull request #496 from alanpoulain/graphql-serialization-groups
[GraphQL] Add documentation about serialization groups
2 parents 439965a + 8a7a1f3 commit c557656

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

core/graphql.md

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -174,3 +174,65 @@ class Book
174174
// ...
175175
}
176176
```
177+
178+
## Serialization Groups
179+
180+
You may want to restrict some resource's attributes to your GraphQL clients.
181+
182+
As described in the [serialization process](serialization.md) documentation, you can use serialization groups to expose only the attributes you want in queries or in mutations.
183+
184+
If the (de)normalization context between GraphQL and REST is different, use the `graphql` key to change it.
185+
186+
Note that:
187+
188+
* A **query** is only using the normalization context.
189+
* A **mutation** is using the denormalization context for its input and the normalization context for its output.
190+
191+
The following example shows you what can be done:
192+
193+
```php
194+
<?php
195+
// api/src/Entity/Book.php
196+
197+
namespace App\Entity;
198+
199+
use ApiPlatform\Core\Annotation\ApiResource;
200+
use Symfony\Component\Serializer\Annotation\Groups;
201+
202+
/**
203+
* @ApiResource(
204+
* attributes={
205+
* "normalization_context"={"groups"={"read"}},
206+
* "denormalization_context"={"groups"={"write"}}
207+
* },
208+
* graphql={
209+
* "query"={"normalization_context"={"groups"={"query"}}},
210+
* "create"={
211+
* "normalization_context"={"groups"={"query"}},
212+
* "denormalization_context"={"groups"={"mutation"}}
213+
* }
214+
* }
215+
* )
216+
*/
217+
class Book
218+
{
219+
// ...
220+
221+
/**
222+
* @Groups({"read", "write", "query"})
223+
*/
224+
private $name;
225+
226+
/**
227+
* @Groups({"read", "mutation"})
228+
*/
229+
private $author;
230+
231+
// ...
232+
}
233+
```
234+
235+
In this case, the REST endpoint will be able to get the two attributes of the book and to modify only its name.
236+
237+
The GraphQL endpoint will be able to query only the name. It will only be able to create a book with an author.
238+
When doing this mutation, the author of the created book will not be returned (the name will be instead).

0 commit comments

Comments
 (0)