Wide banner showcasing playful tech illustrations, including a quirky spider-like character representing API Platform, over a gentle blue and white background.

API Platform: How to Implement Custom Collection Data Providers with Filters?

03/03/2023

In most cases, when you are trying to filter data from your endpoint, default ApiPlatform filters are more than enough to cover all your needs. Sometimes though, additional actions are needed before your collection can be returned to the world.

How to Implement Custom Collection Data Providers with Filters?

This article explains how to implement a custom collection data provider with filters in API Platform version 2.7.4 and is a part of our series of articles on API Platform which you can find on our blog.

Imagine the following scenario: Let's say we have a collection named transactions. We already created endpoints to fetch data GET /api/transactions:

collectionOperations={
    "get"={
        "normalization_context"={"groups"={"transaction:read"}}
    },
}

We also have some filters; for example, employee exact.

>@ApiFilter(SearchFilter::class, properties={"employee"="exact"})

By default when you will call your endpoint with an additional param in the query string project=1, your list will be filtered by only these transactions that are related to a specific project - in this example id 1. The problem starts when you want to do something extra in the DataProvider in this collection. For example, let's filter collection in a data provider based on logged users. If a user has a specific role, then they see all transactions, if they’re a "normal" user then they can only see transactions related to his user.

public function getCollection(string $resourceClass, string $operationName = null, array $context = []): iterable
{
    $queryBuilder = $this->managerRegistry->getRepository(Transaction::class)->createQueryBuilder('t');

    if (!$this->security->isGranted('ROLE_MANAGER')) {
        $queryBuilder
            ->andWhere('ewh.employee = :employee')
            ->setParameter('employee', $this->security->getUser())
        ;
    }

    return $queryBuilder->getQuery()->getResult();
}

However, what’s important to know is that this will remove default filters. Hence, you will not be able to filter by project anymore. What’s the solution?

To force DataProvider to use default filters. In order to do that, we need to inject extensions collection from the api platform.

public function __construct(
    private object $collectionExtensions,
    private ManagerRegistry $managerRegistry,
    private Security $security,
)
{}

Next, we need to inject a specific collection into our service.

App\DataProvider\TransactionsDataProvider:
    tags:
        - { name: 'api_platform.collection_data_provider', priority: 3 }
    autoconfigure: false
    arguments:
        $collectionExtensions: !tagged api_platform.doctrine.orm.query_extension.collection

From this moment forward, we will have all extensions available in our service. Some of them are filters, other ones could be paginations. Now, we can use them to filter our Query by additional criteria - by project in our example. To do that let's use the following code where we are applying each extension.

$queryNameGenerator = new QueryNameGenerator();

/** @var QueryCollectionExtensionInterface $extension */
foreach ($this->collectionExtensions as $extension) {
    $extension->applyToCollection($queryBuilder, $queryNameGenerator, $resourceClass, $operationName, $context);

    if ($extension instanceof QueryResultCollectionExtensionInterface && $extension->supportsResult($resourceClass, $operationName)) {
        return $extension->getResult($queryBuilder);
    }
}

Now, we can finally call our endpoint to check if everything works well. All class including all previous code snippets is available here:

<?php

declare(strict_types=1);

namespace App\DataProvider;

use ApiPlatform\Core\Bridge\Doctrine\Orm\Extension\QueryCollectionExtensionInterface;
use ApiPlatform\Core\Bridge\Doctrine\Orm\Extension\QueryResultCollectionExtensionInterface;
use ApiPlatform\Core\Bridge\Doctrine\Orm\Util\QueryNameGenerator;
use ApiPlatform\Core\DataProvider\CollectionDataProviderInterface;
use ApiPlatform\Core\DataProvider\RestrictedDataProviderInterface;
use App\Entity\Transaction;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Component\Security\Core\Security;

final class TransactionsDataProvider implements CollectionDataProviderInterface, RestrictedDataProviderInterface
{
    private ManagerRegistry $managerRegistry;

    private Security $security;

    private object $collectionExtensions;

    public function __construct(
        private object $collectionExtensions,
        private ManagerRegistry $managerRegistry,
        private Security $security,
    )
    {}

    public function supports(string $resourceClass, string $operationName = null, array $context = []): bool
    {
        return EmployeeWorkingHour::class === $resourceClass;
    }

    public function getCollection(string $resourceClass, string $operationName = null, array $context = []): iterable
    {
        $queryBuilder = $this->managerRegistry->getRepository(Transaction::class)->createQueryBuilder('t');

        if (!$this->security->isGranted('ROLE_MANAGER')) {
            $queryBuilder
                ->andWhere('t.employee = :employee')
                ->setParameter('employee', $this->security->getUser())
            ;
        }

        $queryNameGenerator = new QueryNameGenerator();

        /** @var QueryCollectionExtensionInterface $extension */
        foreach ($this->collectionExtensions as $extension) {
            $extension->applyToCollection($queryBuilder, $queryNameGenerator, $resourceClass, $operationName, $context);

            if ($extension instanceof QueryResultCollectionExtensionInterface && $extension->supportsResult($resourceClass, $operationName)) {
                return $extension->getResult($queryBuilder);
            }
        }

        return $queryBuilder->getQuery()->getResult();
    }
}

Hope this helps!

Ma
Image of Marek Krokwa, confidently posing with arms crossed. He's CTO at Primotly and contributor to our insightful technology articles. Marek is wearing a dark collared shirt and glasses, presenting a smart and approachable look, set against a clean white background
Marek Krokwa
CEO

Latest articles

Illustration for the article about AI and sustainable energy

Innovations | 05/09/2024

Revolutionizing the Energy Sector: The Role of AI in Clean and Renewable Energy Transition

Bernhard Huber

As the global community grapples with the challenges of climate change, the shift towards renewable energy sources has never been more critical. The transition to clean energy is not only essential for reducing carbon emissions but also for ensuring a responsible future for generations to come. At the forefront of this revolution is artificial intelligence (AI), a powerful tool that is transforming how we produce, distribute, and consume energy. AI technologies are increasingly being integrated into the energy system, optimizing everything from energy generation to energy storage, and paving the way for a more efficient and resilient energy infrastructure.

Read more
Preview image for the article about AI for social good

Innovations | 30/08/2024

AI for Social Good: Using AI for Positive Social Impact

Bernhard Huber

Artificial Intelligence is rapidly transforming industries and society, offering innovative solutions to complex challenges. The concept of "AI for Social Good" harnesses this technology to address societal issues, from healthcare and education to environmental sustainability and poverty alleviation. As AI continues to evolve, it is crucial to explore its potential for creating a positive social impact and consider the ethical implications of its deployment. By using AI effectively, we can deliver positive social outcomes and tackle some of the most pressing global challenges.

Read more
Illustration depicting the intersection of ESG (Environmental, Social, and Governance) and AI (Artificial Intelligence) with world map and AI chip icons connected by arrows.

Business | 23/08/2024

Revolutionizing ESG Audits: How AI is Transforming ESG Reporting

Łukasz Kopaczewski

As corporate accountability becomes a focal point for investors and consumers alike, the pressure on companies to deliver precise ESG reports has intensified. A recent study revealed that companies with strong ESG performance see a 10% higher valuation than their peers, highlighting the financial stakes of effective ESG audits. To meet these demands, businesses are increasingly embracing AI-powered solutions that not only enhance the accuracy of ESG audits but also streamline the entire reporting process, setting a new standard for sustainability management.

Read more