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

Tech-themed illustration with icons representing various technology and business areas in which Fractional CTO can help, arranged in a circular pattern on a light background.

Business | 26/07/2024

Fractional CTO Services: Expert Support Tailored to Your Company's Needs

Łukasz Kopaczewski

Can you benefit from the experience of an IT expert without hiring one full-time? Fractional CTOs offer a solution that provides you with a Chief Technology Officer to the extent you need them most. This is an excellent option, particularly for startups and medium-sized companies. In this article, we will explore the essence of the Fractional CTO role and discuss the benefits it can bring to your company. We will also learn about situations where the use of a CTO can be a key element in developing and accelerating technological progress in a company.

Read more
Illustration to the article about AI transparency highlighting main pillars of transparent AI system.

Business | 17/07/2024

The Importance of AI Transparency

Bernhard Huber

From automating routine tasks to making complex decisions, AI systems are becoming integral to many organizations' daily operations. According to statistics general trust in AI is decreasing. As the adoption of AI continues to grow, so does the need for transparency which can improve how AI is seen.

Read more
Preview image for the article about custom software solutions

Business | 11/07/2024

How Custom Software Supports Your Business?

Łukasz Kopaczewski

In many cases, off-the-shelf software cannot be adapted to the specific nature of a given industry or company's business profile. If none of the available solutions meet your expectations, it is worth considering dedicated software. What is it and what benefits can it offer for companies?

Read more