Wide, soft blue background with transparent geometric shapes and connecting lines representing an API platform's data structures and flow for serialization.

API Platform: Serialization & Deserialization

17/02/2023

Serialization is the process of converting complex data structures into formats that can be easily transmitted and stored. Such as JSON-LD, which is the default file format, or XML, CSV and other universally accessible ones. The reverse process, in which the data structure is recreated from a serialized state is known as deserialization.

Both of these processes are essential in facilitating communication between different services.

So, how does this translate to using API Platform?

Serialization in API Platform

Consists of two stages; normalization and encoding.

Normalization transforms an object into a PHP array, which is then encoded and becomes a JSON string.

Deserialization in API Platform

Consists of two stages; decoding and denormalization.

Here, the JSON string is first decoded to become a PHP array and then transformed into an object through denormalization.

Serialization groups in API Platform

Serialization groups in API Platform allow you to choose which fields of an object should be serialized or deserialized. By default, they are defined by using attributes (PHP 8.) or “docstrings” (PHP 7.). The GET method is used to collect data from API, while the PUT, PATCH, and POST methods are used to modify or create new resources.

Examples of using serialization groups can be found below:

<?php


declare(strict_types=1);


namespace App\Entity;


use ApiPlatform\Core\Annotation\ApiResource;
use Symfony\Component\Serializer\Annotation\Groups;


#[ApiResource(
   normalizationContext: ['groups' => ['ticket.read']],
   denormalizationContext: ['groups' => ['ticket.write']],
)]
class Ticket
{
   public int $id;


   #[Groups(['ticket.read', 'ticket.write'])]
   public string $name;


   #[Groups(['ticket.read'])]
   public string $description;


   ...
}

As shown above, either “normalizationContext” or “denormalizationContext” should be added to each entity as it defines serialization groups. Next, in the “$name” field, you can specify the group. For example, when using “ticket.read”, API will retrieve this field through the GET method. To employ the POST/PUT/PATCH methods, use the “ticket.write” group.

Serialization can also be used to handle relations between objects in an API. By default, API platform retrieves relations in byte streams corresponding to the IRI standard which leads directly to a specific resource.

What’s more, serialization groups can be used for custom operations. Below, we present an example of this.

<?php


declare(strict_types=1);


namespace App\Entity;


use ApiPlatform\Core\Annotation\ApiResource;
use Symfony\Component\Serializer\Annotation\Groups;


#[ApiResource(normalizationContext: ['groups' => ['ticket.read']])]
#[Get]
#[Put(normalizationContext: ['groups' => ['ticket.put']])]
class Ticket
{
   public int $id;


   #[Groups(['ticket.read', 'ticket.write'])]
   public string $name;


   #[Groups(['ticket.put'])]
   public string $description;


   ...
}

How to decorate retrieved data in API platform?

Data retrieved by API Platform can also be decorated. This makes it possible to adjust some of the fields. Below, we present how to change the “name” field and add uniqid().

<?php
namespace App\Serializer;


use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
use Symfony\Component\Serializer\SerializerAwareInterface;
use Symfony\Component\Serializer\SerializerInterface;


final class TicketNormalizer implements NormalizerInterface, DenormalizerInterface, SerializerAwareInterface
{
   private NormalizerInterface $decorated;


   public function __construct(NormalizerInterface $decorated)
   {
       if (!$decorated instanceof DenormalizerInterface) {
           throw new \InvalidArgumentException(sprintf('The decorated normalizer must implement the %s.', DenormalizerInterface::class));
       }


       $this->decorated = $decorated;
   }


   public function supportsNormalization($data, $format = null): bool
   {
       return $this->decorated->supportsNormalization($data, $format);
   }


   public function normalize($object, $format = null, array $context = []): array
   {
       $data = $this->decorated->normalize($object, $format, $context);
       if (is_array($data)) {
           $data['name'] = sprintf('%s - %s', $data['name'], uniqid());
       }


       return $data;
   }


   public function supportsDenormalization($data, $type, $format = null): bool
   {
       return $this->decorated->supportsDenormalization($data, $type, $format);
   }


   public function denormalize($data, string $type, string $format = null, array $context = [])
   {
       return $this->decorated->denormalize($data, $type, $format, $context);
   }


   public function setSerializer(SerializerInterface $serializer): void
   {
       if($this->decorated instanceof SerializerAwareInterface) {
           $this->decorated->setSerializer($serializer);
       }
   }
}
Pa
The photo of the article's author - back-end developer at Primotly. The picture shows a professional young man with short hair and glasses looks directly at the camera.
Paweł Turek
Back-end Developer

Latest articles

Illustration of Fractional CTO and their role in a modern company

Business | 29/10/2024

CTO – the Technological Leader Your Company Needs

Łukasz Kopaczewski

Technology drives the growth of modern business. Are you fully leveraging its potential? A Chief Technology Officer (CTO) can help your company optimise IT, enhance security, and implement innovations. Discover how a CTO can support your business.

Read more
Teal and white illustration depicting AI's role in enhancing corporate social responsibility. Icons highlight renewable energy, governance, social equity, and sustainability, with AI technology symbolized at the center.

Business | 24/10/2024

How Artificial Intelligence Enhance Corporate Social Responsibility? AI and CSR

Agata Pater

Corporate Social Responsibility (CSR) is the idea that businesses should not only focus on profits but also care about the world around them. This means that companies are responsible for their impact on the environment and society. CSR can include many actions, such as reducing pollution, improving working conditions, or supporting local communities. When businesses do this, they build trust with customers, employees, and the public. When businesses align CSR with business ethics, they demonstrate a commitment to transparency, fairness, and long-term corporate responsibility. This involves ensuring that operations respect environmental limits and social well-being, fostering positive relationships with stakeholders, and improving supply chain sustainability.

Read more
Abstract illustration of employer branding and its importance in e-commerce industry

Innovations | 18/10/2024

How Does Employer Branding Effectively Build the Image of an Employer in IT?

Julia Zatorska

Employer branding (EB) has become a key tool for attracting and retaining talent in the competitive IT industry. Employer branding is a strategy to build a company's image as an attractive place to work. For tech companies, which constantly face a shortage of qualified employees, effective EB is not only a way to stand out in the market but also to create loyal and motivated teams.

Read more