Accéder au contenu principal

8min.

Comment ajouter des agrégations à une collection API Platform

En juillet 2023, j’ai demandé sur les discussions d’API Platform comment renvoyer des données en plus dans une GetCollection, et surtout comment les documenter. J’avais proposé d’écrire un article si ça intéressait quelqu’un, et en septembre, quelqu’un a dit oui. Le voici, avec trois ans de retard 😅

Section intitulée le-besoinLe besoin

J’ai eu ce besoin pour des endpoints d’API sur redirection.io. Mais pour simplifier l’article nous allons prendre un autre exemple concret : une liste d’articles, sur GET /api/articles. À côté des articles, je veux renvoyer des agrégations : le nombre d’articles par couleur, par taille, etc. Le front s’en sert pour afficher les filtres de la liste, avec le nombre de résultats en face de chaque valeur.

Voici la réponse que je veux obtenir :

{
    "@context": "/api/contexts/Article",
    "@id": "/api/articles",
    "@type": "Collection",
    "totalItems": 1000,
    "member": [
        {
            "@id": "/api/articles/101",
            "@type": "Article",
            "id": 101,
            "color": "blue",
            "size": "M"
        }
    ],
    "view": {
        "@id": "/api/articles?page=1",
        "@type": "PartialCollectionView",
        "first": "/api/articles?page=1",
        "last": "/api/articles?page=34",
        "next": "/api/articles?page=2"
    },
    "aggregations": {
        "color": [
            { "key": "red", "count": 412 },
            { "key": "blue", "count": 230 }
        ],
        "size": [
            { "key": "M", "count": 380 },
            { "key": "L", "count": 262 }
        ]
    }
}

Et je veux que le client TypeScript, généré depuis l’OpenAPI, connaisse le type de ces agrégations, sans que j’aie à l’écrire à la main.

Note : le code de cet article a été testé avec API Platform 4.4, où les clés Hydra n’ont pas de préfixe hydra: par défaut.

Section intitulée pourquoi-api-platform-ne-le-fait-pas-tout-seulPourquoi API Platform ne le fait pas tout seul ?

Le provider d’une GetCollection renvoie un itérable. Le CollectionNormalizer d’Hydra le parcourt pour remplir member, puis le PartialCollectionViewNormalizer ajoute view, avec les liens de pagination. Il n’y a de place pour rien d’autre, ni dans la réponse, ni dans le schéma OpenAPI de la collection.

On pourrait renvoyer un objet avec deux propriétés, articles et aggregations, depuis une opération Get. Mais ce n’est plus une collection : plus de totalItems, plus de liens de pagination, et la liste n’est plus dans member.

Je garde donc une vraie collection, et j’ajoute cinq pièces : des DTO pour les agrégations, un paginator qui les porte, un provider, un normalizer pour la réponse et un décorateur pour le schéma.

Section intitulée les-agregations-sont-des-dtoLes agrégations sont des DTO

Les agrégations sont décrites par des classes PHP, sans #[ApiResource] :

namespace App\Dto;

use ApiPlatform\Metadata\ApiProperty;

final readonly class AggregationEntry
{
    public function __construct(
        #[ApiProperty(required: true)]
        public string $key,
        #[ApiProperty(required: true)]
        public int $count,
    ) {
    }
}
namespace App\Dto;

use ApiPlatform\Metadata\ApiProperty;

final readonly class ArticleAggregations
{
    public function __construct(
        /** @var list<AggregationEntry> */
        #[ApiProperty(required: true)]
        public array $color,
        // Null when the client did not ask for it: the key is then left out of the response.
        /** @var list<AggregationEntry>|null */
        public ?array $size,
    ) {
    }
}

Sans #[ApiProperty(required: true)], API Platform ne marque aucune propriété comme obligatoire, et tout devient optionnel dans le type TypeScript. Pour size, qui peut être null, j’y reviendrai.

Puis je déclare ce type sur l’opération, dans ses extraProperties :

#[ApiResource(
    operations: [
        new Get(/* ... */),
        new GetCollection(
            provider: ArticleCollectionProvider::class,
            extraProperties: ['aggregations' => ArticleAggregations::class],
        ),
    ],
)]
final readonly class Article

C’est la seule déclaration. Le normalizer et le schéma la lisent tous les deux.

Section intitulée un-paginator-qui-porte-les-agregationsUn paginator qui porte les agrégations

Le paginator enveloppe un paginator d’API Platform et lui délègue tout :

namespace App\State\Pagination;

use ApiPlatform\State\Pagination\PaginatorInterface;

/**
 * @template T of object
 *
 * @implements \IteratorAggregate<T>
 * @implements PaginatorInterface<T>
 */
final readonly class AggregatedPaginator implements \IteratorAggregate, PaginatorInterface
{
    public function __construct(
        /** @var PaginatorInterface<T> */
        private PaginatorInterface $paginator,
        private object $aggregations,
    ) {
    }

    public function getAggregations(): object
    {
        return $this->aggregations;
    }

    public function getIterator(): \Traversable
    {
        yield from $this->paginator;
    }

    public function count(): int
    {
        return $this->paginator->count();
    }

    public function getCurrentPage(): float
    {
        return $this->paginator->getCurrentPage();
    }

    public function getItemsPerPage(): float
    {
        return $this->paginator->getItemsPerPage();
    }

    public function getLastPage(): float
    {
        return $this->paginator->getLastPage();
    }

    public function getTotalItems(): float
    {
        return $this->paginator->getTotalItems();
    }
}

Le point important, c’est PaginatorInterface. Les normalizers d’Hydra testent cette interface pour écrire totalItems et les liens de pagination. Sans elle, les liens disparaissent, et totalItems ne compte plus que les articles de la page courante.

Section intitulée le-providerLe provider

Le provider demande au repository la page, le total et les agrégations, en un seul appel et avec les mêmes filtres. Comme ça, les compteurs correspondent toujours aux résultats :

namespace App\State;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\Pagination\Pagination;
use ApiPlatform\State\Pagination\TraversablePaginator;
use ApiPlatform\State\ProviderInterface;
use App\ApiResource\Article;
use App\Repository\ArticleRepository;
use App\State\Pagination\AggregatedPaginator;

/**
 * @implements ProviderInterface<Article>
 */
final readonly class ArticleCollectionProvider implements ProviderInterface
{
    public function __construct(
        private ArticleRepository $articleRepository,
        private Pagination $pagination,
    ) {
    }

    /** @return AggregatedPaginator<Article> */
    public function provide(Operation $operation, array $uriVariables = [], array $context = []): AggregatedPaginator
    {
        $page = $this->pagination->getPage($context);
        $itemsPerPage = $this->pagination->getLimit($operation, $context);

        $result = $this->articleRepository->search($context['filters'] ?? [], $page, $itemsPerPage);

        return new AggregatedPaginator(
            new TraversablePaginator(new \ArrayIterator($result->articles), $page, $itemsPerPage, $result->total),
            $result->aggregations,
        );
    }
}

TraversablePaginator vient d’API Platform : il porte les articles de la page et les informations de pagination. $result->aggregations est un ArticleAggregations.

Je ne montre pas le repository, il dépend trop de votre stockage. Sur redirection.io, c’est ClickHouse 💛.

Et une agrégation coûte cher à calculer. Sur redirection.io, le front envoie dans le paramètre activeAggregations la liste de celles dont il a besoin, et le provider ne calcule que celles-là. Les autres restent à null, d’où le ?array de size.

Section intitulée le-normalizerLe normalizer

Il écrit les agrégations dans la réponse. Je décore le normalizer de la vue partielle d’Hydra :

namespace App\Serializer;

use App\State\Pagination\AggregatedPaginator;
use Symfony\Component\DependencyInjection\Attribute\AsDecorator;
use Symfony\Component\DependencyInjection\Attribute\AutowireDecorated;
use Symfony\Component\Serializer\Normalizer\AbstractObjectNormalizer;
use Symfony\Component\Serializer\Normalizer\NormalizerAwareInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;

#[AsDecorator('api_platform.hydra.normalizer.partial_collection_view')]
final class AggregatedCollectionNormalizer implements NormalizerInterface, NormalizerAwareInterface
{
    private NormalizerInterface $serializer;

    public function __construct(
        #[AutowireDecorated]
        private readonly NormalizerInterface $decorated,
    ) {
    }

    public function normalize(mixed $data, ?string $format = null, array $context = []): array
    {
        $normalized = (array) $this->decorated->normalize($data, $format, $context);

        if (!$data instanceof AggregatedPaginator) {
            return $normalized;
        }

        $aggregationsClass = $context['operation']?->getExtraProperties()['aggregations'] ?? null;
        if (null === $aggregationsClass || !$data->getAggregations() instanceof $aggregationsClass) {
            throw new \LogicException(\sprintf('The operation declares aggregations of type "%s", but the provider returned "%s".', $aggregationsClass ?? 'none', $data->getAggregations()::class));
        }

        // Plain JSON: in JSON-LD, the serializer turns the DTOs into nodes (@id, @type) and the
        // lists into Hydra collections. Keep in sync with AggregatedCollectionSchemaFactory.
        // Null values are left out: API Platform 4.4 documents a nullable list as a plain array,
        // so a nullable property must be an optional key, not a null one.
        $normalized['aggregations'] = $this->serializer->normalize($data->getAggregations(), 'json', [
            AbstractObjectNormalizer::SKIP_NULL_VALUES => true,
        ]);

        return $normalized;
    }

    public function supportsNormalization(mixed $data, ?string $format = null, array $context = []): bool
    {
        return $this->decorated->supportsNormalization($data, $format, $context);
    }

    public function getSupportedTypes(?string $format): array
    {
        return $this->decorated->getSupportedTypes($format);
    }

    public function setNormalizer(NormalizerInterface $normalizer): void
    {
        $this->serializer = $normalizer;

        if ($this->decorated instanceof NormalizerAwareInterface) {
            $this->decorated->setNormalizer($normalizer);
        }
    }
}

D’abord, setNormalizer(). Le normalizer de collection d’origine a besoin du serializer pour normaliser chaque article. Mais c’est notre décorateur qui le reçoit, et il doit le transmettre. Sans ça, la requête finit en erreur 500 :

Typed property ApiPlatform\Serializer\AbstractCollectionNormalizer::$normalizer must not be accessed before initialization

Ensuite, le format json. Au premier essai, je normalisais les agrégations avec le format et le contexte de la collection. Le serializer en faisait des nœuds JSON-LD, avec un @id en /.well-known/genid/… et un @type, et chaque liste devenait une collection Hydra avec un member. Rien à voir avec le schéma. Avec le format json, la réponse colle au schéma.

Enfin, SKIP_NULL_VALUES. API Platform 4.4 documente une liste nullable comme un tableau, sans null. Une agrégation à null disparaît donc de la réponse, et le schéma la déclare optionnelle, puisque size n’a pas de required: true.

Et si le provider renvoie un autre type que celui déclaré, la LogicException le dit tout de suite, plutôt qu’une documentation fausse.

Section intitulée et-si-le-serializer-est-trop-lentEt si le Serializer est trop lent ?

Sur redirection.io, le Serializer prenait environ 30 ms, et jusqu’à 64 ms, sur les agrégations d’une liste de logs. J’y utilise donc AutoMapper, qui descend à environ 1 ms. Il génère une classe PHP pour chaque mapping, et la met en cache.

Après un composer require jolicode/automapper et l’ajout de son bundle dans config/bundles.php, voici ce qui change dans le normalizer :

use AutoMapper\AutoMapperInterface;
use AutoMapper\MapperContext;

#[AsDecorator('api_platform.hydra.normalizer.partial_collection_view')]
final readonly class AggregatedCollectionNormalizer implements NormalizerInterface, NormalizerAwareInterface
{
    public function __construct(
        #[AutowireDecorated]
        private NormalizerInterface $decorated,
        private AutoMapperInterface $autoMapper,
    ) {
    }

    public function normalize(mixed $data, ?string $format = null, array $context = []): array
    {
        // ...

        $normalized['aggregations'] = $this->autoMapper->map($data->getAggregations(), 'array', [
            MapperContext::SKIP_NULL_VALUES => true,
        ]);

        return $normalized;
    }

    // ...

    public function setNormalizer(NormalizerInterface $normalizer): void
    {
        if ($this->decorated instanceof NormalizerAwareInterface) {
            $this->decorated->setNormalizer($normalizer);
        }
    }
}

AutoMapper ne connaît pas JSON-LD : plus besoin de forcer le format json, ni de garder le serializer. setNormalizer() ne sert plus qu’à le transmettre au normalizer décoré, et la classe devient readonly. Le schéma ne change pas, et la réponse contient les mêmes données.

Section intitulée le-schema-openapiLe schéma OpenAPI

Reste la documentation. Je décore le SchemaFactory d’API Platform :

namespace App\JsonSchema;

use ApiPlatform\JsonSchema\Schema;
use ApiPlatform\JsonSchema\SchemaFactoryInterface;
use ApiPlatform\Metadata\CollectionOperationInterface;
use ApiPlatform\Metadata\Operation;
use Symfony\Component\DependencyInjection\Attribute\AsDecorator;
use Symfony\Component\DependencyInjection\Attribute\AutowireDecorated;

// Priority -1: wraps the Hydra schema factory (priority 0), which builds the collection "allOf".
#[AsDecorator('api_platform.json_schema.schema_factory', priority: -1)]
final readonly class AggregatedCollectionSchemaFactory implements SchemaFactoryInterface
{
    public function __construct(
        #[AutowireDecorated]
        private SchemaFactoryInterface $decorated,
    ) {
    }

    public function buildSchema(string $className, string $format = 'json', string $type = Schema::TYPE_OUTPUT, ?Operation $operation = null, ?Schema $schema = null, ?array $serializerContext = null, bool $forceCollection = false): Schema
    {
        $schema = $this->decorated->buildSchema($className, $format, $type, $operation, $schema, $serializerContext, $forceCollection);

        $aggregationsClass = $operation?->getExtraProperties()['aggregations'] ?? null;
        if (null === $aggregationsClass || 'jsonld' !== $format || Schema::TYPE_OUTPUT !== $type || !$operation instanceof CollectionOperationInterface) {
            return $schema;
        }

        $aggregationsSchema = new Schema($schema->getVersion());
        $aggregationsSchema->setDefinitions($schema->getDefinitions());
        // The aggregations are normalized in plain JSON, see AggregatedCollectionNormalizer.
        $aggregationsSchema = $this->decorated->buildSchema($aggregationsClass, 'json', $type, null, $aggregationsSchema);

        $allOf = $schema['allOf'];
        $allOf[] = [
            'type' => 'object',
            'required' => ['aggregations'],
            'properties' => [
                'aggregations' => ['$ref' => $aggregationsSchema['$ref']],
            ],
        ];
        $schema['allOf'] = $allOf;

        return $schema;
    }
}

Avez-vous remarqué la priorité ? Pour une collection, c’est le SchemaFactory d’Hydra qui construit le schéma : un allOf avec la base commune des collections et la liste member. Il décore le service avec la priorité 0. Avec –1, notre décorateur passe après lui, et trouve un allOf auquel ajouter aggregations.

Voici ce qu’on obtient dans la réponse documentée de GET /api/articles, à côté de member :

{
    "type": "object",
    "required": ["aggregations"],
    "properties": {
        "aggregations": { "$ref": "#/components/schemas/ArticleAggregations" }
    }
}

Section intitulée le-client-typescriptLe client TypeScript

Et voilà ce que génère orval, sans une ligne écrite à la main :

export interface AggregationEntry {
  key: string;
  count: number;
}

export interface ArticleAggregations {
  color: AggregationEntry[];
  size?: AggregationEntry[];
}

export type ApiArticlesGetCollection200 = HydraCollectionBaseSchema & {
  member: ArticleJsonld[];
  aggregations: ArticleAggregations;
};

Le compilateur refuse maintenant response.aggregations.brand, et il oblige à vérifier size avant de le lire.

Section intitulée les-limitesLes limites

  • Une map d’objets, comme array<string, AggregationEntry>, est bien documentée. Une map de listes, comme array<string, list<AggregationEntry>>, sort en "type": "unknown_type".
  • Une collection demandée en application/json reste un tableau nu, sans agrégations, ni dans la réponse, ni dans le schéma.

Section intitulée conclusionConclusion

Je trouve que le code est propre, il y a des types absolument partout, et le front peut s’auto-valider ! J’aime bien !

Merci à Joël, qui a écrit la première version du paginator et du normalizer. Et merci à Joël et Baptiste pour AutoMapper.

Commentaires et discussions

Nos formations sur ce sujet

Notre expertise est aussi disponible sous forme de formations professionnelles !

Voir toutes nos formations

Ces clients ont profité de notre expertise