sajad torkamani

Create a class that implements the ItemDataProviderInterface like so:

<?php
// src/DataProvider/BlogPostItemDataProvider.php

namespace App\DataProvider;

use ApiPlatform\Core\DataProvider\ItemDataProviderInterface;
use ApiPlatform\Core\DataProvider\RestrictedDataProviderInterface;
use App\Entity\BlogPost;

final class BlogPostItemDataProvider implements ItemDataProviderInterface, RestrictedDataProviderInterface
{
    public function supports(string $resourceClass, string $operationName = null, array $context = []): bool
    {
        return BlogPost::class === $resourceClass;
    }

    public function getItem(string $resourceClass, $id, string $operationName = null, array $context = []): ?BlogPost
    {
        // Retrieve the blog post item from somewhere then return it or null if not found
        return new BlogPost($id);
    }
}

The getItem method should return a resource or null if no result can be found.

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 item data provider.

Sources / related