How do I generate a subresources route in ApiPlatform?

Viewed 57

Given a $question object, how do I get the subresource route?

#[ORM\Entity]
#[ApiResource]
class Question
{
    #[ORM\OneToMany(targetEntity: Answer::class, mappedBy: 'question']
    #[ApiSubresource]
    public $answers;

$question = $questionRepo->find(42);

// /api/questions
$iriConverter->getIriFromResourceClass($question::class); 
// /api/questions/42
$iriConverter->getIriFromItem($question); 

# /api/questions/42/answers
$iriConverter->getSubresourceIriFromResourceClass($question, ['answers'] ); // NOPE!

What are the arguments to getSubresourceIriFromResourceClass()?

1 Answers

If you check the test https://github.com/api-platform/core/blob/ffda414da9fd025b360fd7d5a5864fef6b5b9729/tests/Bridge/Symfony/Routing/IriConverterTest.php#L198, you can see that you need to do something like this:

$iriConverter->getSubresourceIriFromResourceClass(
    $question::class,
    [
        'subresource_identifiers' => ['id' => $questionId],
        'subresource_resources' => [Answer::class => null],
    ]
); 

Note that in API Platform 2.7/3, the concept of subresources does not exist anymore, and you need to follow this documentation in order to do the same as before: https://api-platform.com/docs/main/core/subresources.

Related