API і серіалізація

← API і серіалізація

Ashterix

feat(seo): og:image size for front matter images; short titles and explicit descriptions for From Magento to Symfony

uk/articles/magento-to-symfony/data/api.md +2 −1

API і серіалізація

Magento генерує REST і SOAP з інтерфейсів сервісів. У Symfony є два шляхи: звичайні контролери із Serializer для контрольованого API або API Platform, коли треба швидко отримати CRUD, фільтри, пагінацію й OpenAPI з атрибута на сутності.

Magento · webapi.xml

<route url="/V1/faq/questions/:id" method="GET">
    <service class="Vendor\Faq\Api\QuestionRepositoryInterface"
             method="getById"/>
    <resources>
        <resource ref="anonymous"/>
    </resources>
</route>

Symfony · контролер + групи серіалізації

use Symfony\Component\Serializer\Attribute\Groups;

class Question
{
    #[Groups(['question:read'])]
    private ?int $id = null;

    #[Groups(['question:read'])]
    private string $title;
}

#[Route('/api/questions/{id}', methods: ['GET'])]
public function show(Question $question): JsonResponse
{
    return $this->json($question, context: [
        'groups' => ['question:read'],
    ]);
}

Symfony · API Platform: найближче до автогенерації

#[ApiResource(
    operations: [
        new Get(),
        new GetCollection(),
        new Post(security: "is_granted('ROLE_FAQ_EDITOR')"),
    ],
    normalizationContext: ['groups' => ['question:read']],
)]
#[ORM\Entity]
class Question { /* … */ }

Віддавати сутності напряму зручно, але публічний API краще будувати на окремих DTO, щоб зміна схеми БД не ламала контракт. GraphQL: API Platform або overblog/graphql-bundle.