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
Zdjęcie autora artykułu - back-end developera w Primotly. Na zdjęciu profesjonalny młody mężczyzna z krótkimi włosami i okularami patrzy bezpośrednio w kamerę.
Paweł Turek
Back-end Developer

Najnowsze artykuły

Ilustracja obrazująca powiązanie pomiędzy AI a odnawialną energią

Innovations | 05/09/2024

Rewolucja w sektorze energetycznym: AI w transformacji energetycznej

Bernhard Huber

Ponieważ globalna społeczność zmaga się z wyzwaniami związanymi ze zmianami klimatycznymi, przejście na odnawialne źródła energii nigdy nie było bardziej istotnym zagadnieniem. Przejście na czystą energię jest nie tylko niezbędne do zmniejszenia emisji dwutlenku węgla, ale także do zapewnienia odpowiedzialnej przyszłości przyszłym pokoleniom. Na czele tej rewolucji stoi sztuczna inteligencja - potężne narzędzie, które zmienia sposób, w jaki produkujemy, dystrybuujemy i zużywamy energię. Technologie sztucznej inteligencji są coraz częściej integrowane z systemem energetycznym, optymalizując wszystko, od wytwarzania energii po jej magazynowanie.

Szczegóły
Ilustracja artykułu o wpływie AI na dobro społeczeństwa i środowiska (części składowych ESG)

Innovations | 30/08/2024

Sztuczna inteligencja dla dobra społecznego: Wykorzystanie sztucznej inteligencji dla pozytywnego wpływu społecznego

Bernhard Huber

Sztuczna inteligencja szybko przekształca branże i społeczeństwo, oferując innowacyjne rozwiązania złożonych wyzwań. Koncepcja „AI for Social Good” wykorzystuje tę technologię do rozwiązywania problemów społecznych, od opieki zdrowotnej i edukacji po zrównoważony rozwój środowiska i łagodzenie ubóstwa. Ponieważ sztuczna inteligencja wciąż ewoluuje, kluczowe znaczenie ma zbadanie jej potencjału w zakresie wywierania pozytywnego wpływu społecznego i rozważenie etycznych konsekwencji jej wdrażania. Dzięki efektywnemu wykorzystaniu sztucznej inteligencji możemy osiągnąć pozytywne wyniki społeczne i stawić czoła niektórym z najpilniejszych globalnych wyzwań.

Szczegóły
Ilustracja przedstawiająca przecięcie ESG (Środowiskowe, Społeczne i Ład Korporacyjny) oraz AI (Sztuczna Inteligencja) z ikonami mapy świata i chipu AI połączonymi strzałkami.

Business | 23/08/2024

Rewolucja w audytach ESG: Jak AI zmienia raportowanie ESG w biznesie?

Łukasz Kopaczewski

Niedawne badanie wykazało, że firmy o dobrych wynikach ESG mają o 10% wyższą wycenę niż ich konkurenci. Aby sprostać tym wymaganiom, firmy coraz częściej stosują rozwiązania oparte na sztucznej inteligencji, które nie tylko zwiększają dokładność audytów ESG, ale także usprawniają cały proces raportowania, wyznaczając nowy standard zarządzania zrównoważonym rozwojem.

Szczegóły