API and serialization

โ† API and serialization

Ashterix

docs(articles): English translation of From Magento to Symfony

en/articles/magento-to-symfony/data/api.md new file +55 โˆ’0

1 + # API and serialization
2 +
3 + Magento generates REST and SOAP from service interfaces. In Symfony there are two paths: regular controllers with the Serializer for an API you control, or API Platform when you need CRUD, filters, pagination and OpenAPI quickly from an attribute on the entity.
4 +
5 + **Magento** ยท webapi.xml
6 +
7 + ```xml
8 + <route url="/V1/faq/questions/:id" method="GET">
9 + <service class="Vendor\Faq\Api\QuestionRepositoryInterface"
10 + method="getById"/>
11 + <resources>
12 + <resource ref="anonymous"/>
13 + </resources>
14 + </route>
15 + ```
16 +
17 + **Symfony** ยท controller + serialization groups
18 +
19 + ```php
20 + use Symfony\Component\Serializer\Attribute\Groups;
21 +
22 + class Question
23 + {
24 + #[Groups(['question:read'])]
25 + private ?int $id = null;
26 +
27 + #[Groups(['question:read'])]
28 + private string $title;
29 + }
30 +
31 + #[Route('/api/questions/{id}', methods: ['GET'])]
32 + public function show(Question $question): JsonResponse
33 + {
34 + return $this->json($question, context: [
35 + 'groups' => ['question:read'],
36 + ]);
37 + }
38 + ```
39 +
40 + **Symfony** ยท API Platform: the closest thing to autogeneration
41 +
42 + ```php
43 + #[ApiResource(
44 + operations: [
45 + new Get(),
46 + new GetCollection(),
47 + new Post(security: "is_granted('ROLE_FAQ_EDITOR')"),
48 + ],
49 + normalizationContext: ['groups' => ['question:read']],
50 + )]
51 + #[ORM\Entity]
52 + class Question { /* โ€ฆ */ }
53 + ```
54 +
55 + Exposing entities directly is convenient, but a public API is better built on separate DTOs, so that a database schema change doesn't break the contract. GraphQL: API Platform or `overblog/graphql-bundle`.