Defining API-Platform Resources & Serialization Groups in YAML

API Platform is a powerful platform to build REST and GraphQL APIs. Resource configuration can be executed in annotation, YAML, or XML.

The docs follow an approach which demonstrates how to configure via annotation first, then often but not always examples are provided for YAML, and less frequently, XML.

Annotating entities is the most intuitive method at first, however the readability of your entity decreases as the complexity of your API increases. This is the reason I lean toward defining AP resources and serialization in YAML config.

Serialization Groups

Serialization groups are one of the most powerful elements of API Platform. (AP)

AP elegantly uses the Symfony Serializer component to normalize and denormalize resource data.

  • Normalize: Transform values from database into what is delivered by the API
  • Think of this as a `read`
  • Denormalize: Transform values submitted to the API, into database values
  • Think of this as a `write`

After creating a group named `read` for normalization, and a group named `write` for denormalization, we can apply the groups to each property based on if they should be readable or writable.

Let's look at the annotated `Book` entity from the serialization documentation.

// src/Entity/Book.php

namespace App\Entity;

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

 * @ApiResource(
 *     normalizationContext={"groups"={"read"}},
 *     denormalizationContext={"groups"={"write"}}
 * )
class Book
     * @Groups({"read", "write"})
    private $name;

     * @Groups("write")
    private $author;

    // ...

Let's take a step back to the point of annotation clutter. I'm just demonstrating serializer groups here, but if we had annotation for operations, access, etc... it would be much more difficult to reason about an entity file. This is why I prefer YAML, for API resource documentation at least.

To migrate the config above to YAML, you will need 2 files:

# config/api_platform/resources.yaml
            groups: ['read']
            groups: ['write']


The next file is in `config/serialization` because it just follows the standard serializer component approach. If you haven't explored serializers before, consider this use case to hit the ground running a little faster.

# config/serialization/Book.yaml
            groups: ['read', 'write']
            groups: ['write']


Once these are in place, your API should work as expected without any API Platform related annotation in your entity.

Up Next

Ready To Get Started?

Schedule a complimentary 30-minute strategy consultation with one of our Drupal experts as early as today. We promise...they don't bite!