Implement a custom collection data provider in API Platform
1 June 2022 (Updated 1 June 2025)
Create a class that implements the CollectionDataProviderInterface like so:
<?php
// src/DataProvider/BlogPostCollectionDataProvider.php
namespace App\DataProvider;
use ApiPlatform\Core\DataProvider\ContextAwareCollectionDataProviderInterface;
use ApiPlatform\Core\DataProvider\RestrictedDataProviderInterface;
use App\Entity\BlogPost;
final class BlogPostCollectionDataProvider implements ContextAwareCollectionDataProviderInterface, RestrictedDataProviderInterface
{
public function supports(string $resourceClass, string $operationName = null, array $context = []): bool
{
return BlogPost::class === $resourceClass;
}
public function getCollection(string $resourceClass, string $operationName = null, array $context = []): iterable
{
// Retrieve the blog post collection from somewhere
yield new BlogPost(1);
yield new BlogPost(2);
}
}
The getCollection method must return an array or a Traversable.
The additional RestrictedDataProviderInterface lets you restrict the data provider based on a condition. In this case, we restrict it to the BlogPost resource.
By default, this data provider will be automatically registered with Symfony’s service container.
Here‘s another example of a custom collection data provider.
Tagged:
API Platform recipes
Thanks for your comment 🙏. Once it's approved, it will appear here.
Leave a comment