API Platform 3

A suitable serialization with

Mathias Arlaud

@matarld
mtarld
les-tilleuls.coop
@matarld
@matarld

Representing data structures in a format that can be sent or persisted in order to be reconstructed later

Binary, textual

Construction pattern

Databases, flat files, APIs

Anywhere, interoperable

Serialization

@matarld

https://symfony.com/doc/current/components/serializer.html

Serialization

@matarld
#[ApiResource]
class Robot
{
    public int $id;

    public string $name;

    public string $mission;

    public string $unofficialMission;
}

Beep-boop!

@matarld
#[ApiResource]
class Robot
{
    public int $id;

    public string $name;

    public string $mission;

    public string $unofficialMission;
}
{
  "id": 1,
  "name": "Persévérance",
  "mission": "Find life on Mars",
  "unofficialMission": "Wipe out all life on Mars"
}
> curl /api/robots/1.json

Beep-boop!

@matarld

Customizing serializion

#[ApiResource]
class Robot
{
    public int $id;

    public string $name;

    public string $mission;

    public string $unofficialMission;
}
{
  "id": 1,
  "name": "Persévérance",
  "mission": "Find life on Mars",
  "unofficialMission": "Wipe out all life on Mars"
}
> curl /api/robots/1.json
@matarld
#[ApiResource]
class Robot
{
  public int $id;

  public string $name;

  public string $mission;

  #[Ignore]
  public string $unofficialMission;
}

Ignore/ApiProperty

@matarld
#[ApiResource]
class Robot
{
  public int $id;

  public string $name;

  public string $mission;

  #[ApiProperty(readable: false, writable: false)]
  public string $unofficialMission;
}

Ignore/ApiProperty

@matarld
#[ApiResource]
class Robot
{
  // ...

  #[ApiProperty(readable: false, writable: false)]
  public string $unofficialMission;
}
#[ApiResource]
class Robot
{
  // ...

  #[Ignore]
  public string $unofficialMission;
}
> curl /api/robots/1.json
> curl /api/robots.json
...

Groups!

Ignore/ApiProperty

@matarld
public function serialize($data, string $format, array $context = []);

Groups

@matarld
class Robot
{
  #[Groups(['group-one', 'group-two'])]
  public string $name;

  #[Groups(['group-one'])]
  public string $mission;

  public string $unofficialMission;
}

Groups

@matarld
class Robot
{
  #[Groups(['group-one', 'group-two'])]
  public string $name;

  #[Groups(['group-one'])]
  public string $mission;

  public string $unofficialMission;
}
serialize(..., ['groups' => ['group-one']]);
serialize(..., ['groups' => ['group-two']]);
{"name": "foo", "mission": "bar"}
{"name": "foo"}

Groups

@matarld
> curl /api/robots/1.json
['item']
> curl /api/robots.json
['list']
#[ApiResource(
  new Get(
    normalizationContext: ['groups' => ['item']],
  ),
  new GetCollection(
    normalizationContext: ['groups' => ['list']],
  ),
)]

Groups and API Platform

@matarld
> curl /api/robots/1.json

SerializeListener

ContextBuilder, Serializer

(RespondListener)

Yep, I know it!

ViewEvent

Does anyone know how to convert a        to a       ?

Controller
Response

API Platform and Symfony

@matarld

ContextBuilders

#[ApiResource(
  normalizationContext: ['groups' => ['read']],
)]
class Robot
{
  #[Groups(['read'])]
  public string $name;

  #[Groups(['read'])]
  public string $mission;
  
  #[Groups(['secret_service'])]
  public string $unofficialMission;
}
@matarld

ContextBuilders

SerializeListener
ContextBuilder
interface SerializerContextBuilderInterface {

  public function createFromRequest(
    Request $request,
    bool $normalization,
    ?array $attributes = null,
  ): array;
  
}
Serializer
@matarld

ContextBuilders

class SecretServiceContextBuilder implements SerializerContextBuilderInterface
{
  public function createFromRequest(...): array
  {
    // $this->decorated <=> 'api_platform.serializer.context_builder' service
    $context = $this->decorated->createFromRequest(...);
    
    if (Robot::class === ($context['resource_class'] ?? null)
      && $this->authorizationChecker->isGranted('ROLE_SECRET_SERVICE')
    ) {
      $context['groups'][] = 'secret_service';
    }
    
    return $context;
  }
}

Context used by the serializer

Custom logic

API Platform generated context

@matarld

ApiProperty::security

ExpressionLanguage

user, object, is_granted, ...
#[ApiResource(normalizationContext: ['groups' => ['read']])]
class Robot
{ 




  #[Groups(['read'])]
  public string $unofficialMission;
}
#[ApiProperty(
  security: 'is_granted("ROLE_SECRET_SERVICE")',
)]
@matarld

Serializers

#[ApiResource(normalizationContext: ['groups' => ['read']])]
class Robot {
  #[Groups(['read'])]
  public string $name;
  
  #[Groups(['creator'])]
  public string $mentalHealth;
  
  public User $creator;
}
@matarld

Serializers

SerializeListener
ContextBuilder
interface NormalizerInterface
{
  public function normalize(
    $data,
    string $format = null,
    array $context = []
  );

  public function supportsNormalization(
    $data,
    string $format = null,
    array $context = []
  ): bool;
}
Serializer
@matarld

Serializers

class RobotNormalizer implements NormalizerInterface
{
  public function normalize(...)
  {
    if ($this->security->getUser() === $data->creator) {
      $context['groups'][] = 'creator';
    }

    return $this->normalizer->normalize($data, $format, $context);
  }

  public function supportsNormalization(...): bool
  {
    return ... && $data instanceof Robot;
  }
}

Scope the normalizer

Custom logic

Regular normalization

@matarld

ApiProperty::security

#[ApiResource(normalizationContext: ['groups' => ['read']])]
class Robot
{ 




  #[Groups(['read'])]
  public string $unofficialMission;
}
#[ApiProperty(
  security: 'object.creator == user',
)]
@matarld

Defaults

#[ApiResource(
  new Get(
    normalizationContext: ['groups' => ['read']],
  ),
  new GetCollection(
    normalizationContext: ['groups' => ['read']],
  ),
)]
class Robot {}
#[ApiResource(
  new Get(
    normalizationContext: ['groups' => ['read']],
  ),
  new GetCollection(
    normalizationContext: ['groups' => ['read']],
  ),
)]
class Datasheet {}
@matarld

Defaults

#[ApiResource(
  normalizationContext: ['groups' => ['read']],
)]
class Datasheet {}
#[ApiResource(
  normalizationContext: ['groups' => ['read']],
)]
class Robot {}
@matarld

Defaults

#[ApiResource]
class Datasheet {}
#[ApiResource]
class Robot {}
api_platform:
  defaults:
    normalizationContext:
      groups: ["read"]
      
    # ...
    

api_platform.yaml

@matarld

ResourceMetadata

#[ApiResource]
class Robot {
  #[Groups(['read'])]
  public Datasheet $datasheet;
}

#[ApiResource]
class Datasheet {
    #[Groups(['read'])]
    public string $reference;

    #[Groups(['read'])]
    public array $specs;
}
{
  "datasheet": {
    "reference": "PE-01",
    "specs": ["lot of data", "..."]
  }
}
@matarld

ResourceMetadata

#[ApiResource(
  normalizationContext: ['groups' => ['robot:read']],
)]
class Robot {
  #[Groups(['robot:read'])]
  public Datasheet $datasheet;
}

#[ApiResource(
  normalizationContext: ['groups' => ['datasheet:read']],
)]
class Datasheet {
    #[Groups(['datasheet:read', 'robot:read'])]
    public string $reference;

    #[Groups(['datasheet:read'])]
    public array $specs;
}
{
  "datasheet": {
    "reference": "PE-01"
  }
}
@matarld
ResourceMetadataCollectionFactory
App\Entity\Robot
SerializeListener
Serializer
ResourceMetadataCollection
ContextBuilder
Operation

ResourceMetadata

@matarld
class GroupResourceMetadataCollectionFactory implements ResourceMetadataCollectionFactoryInterface
{
  public function create(string $resourceClass): ResourceMetadataCollection
  {
    $metadata = $this->decorated->create($resourceClass);
    
    foreach ($resources as $i => $resource) {
        $metadata[$i] = $resource->withOperations($this->addGroupsToOperations($resource));
    }
    
    return $metadata;
  }
    
  // Return operations with dynamic groups (eg: robot:read, robot:list, or robot:item).
  private function addGroupsToOperations(ApiResource $metadata): ApiResource {}
}

ResourceMetadata

@matarld
SerializeListener
Serializer
ContextBuilder
#[ApiResource]
class Robot {
  #[Groups(['robot:read'])]
  public Datasheet $datasheet;
}

#[ApiResource]
class Datasheet {
    #[Groups(['datasheet:read', 'robot:read'])]
    public string $reference;

    #[Groups(['datasheet:read'])]
    public array $specs;
}

ResourceMetadata

@matarld

Wrap it up!

ViewEvent
ContextBuilder
By resource type
By operation
By request
Defaults
By operation
Documentation friendly
ResourceMetadata
By resource type
By operation
Documentation friendly
$context
@matarld

Wrap it up!

ViewEvent
Serializer
By context
By resource instance
$context, $data
{"..."}

Thanks!

@matarld

New resource

class Robot
{
  public string $name;
  
  public string $mission;
  
  public int $battery;

  public Datasheet $datasheet;
}
class Astronaut
{
  public string $name;
  
  public string $task;
  
  public bool $hasOxygen;
}
@matarld

New resource

#[ApiResource(
  operations: [
    new Get(),
  ]
)]
class Robot {}
#[ApiResource(
  operations: [
    new GetCollection(
      uriTemplate: '/robots',
      provider: AstronautsProvider::class,
    ),
  ]
)]
class Astronaut {}
@matarld

New resource

final class AstronautsProvider implements ProviderInterface
{
  public function provide($operation, $uriVariables, $context): array
  {
    $robots = $this->robotRepository->findAll();
    
    return array_map(static function (Robot $r): Astronaut {
      $a = new Astronaut();
      $a->name = $r->name;
      $a->task = $r->mission;
      $a->hasOxygen = $r->battery > 0;

      return $a;
    }, $robots);
}
@matarld

Wrap it up!

New resource
By resource type
By operation
Documentation friendly

[API Days] A suitable serialization with API Platform and Symfony

By Mathias Arlaud

[API Days] A suitable serialization with API Platform and Symfony

  • 1,744