API and serialization

← API and serialization

Ashterix

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

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

API and serialization

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.

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 · controller + serialization groups

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: the closest thing to autogeneration

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

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.