I’m currently working on a Symfony project using API Platform, and I’m running into some confusion regarding the uriTemplate system and how it handles variable IDs.
I have an entity called Article, and I want to set up a custom collection route that uses a parameter other than {id}. Specifically, I want to use {categoryId}. However, I’m encountering issues when I try to do this, and I’m not sure why API Platform seems to insist on using {id}.
Here is an example of my Article entity configuration:
<?php
use ApiPlatformMetadataApiResource;
use ApiPlatformMetadataGet;
use ApiPlatformMetadataGetCollection;
use AppStateArticlesByCategoryProvider;
#[ApiResource(
operations: [
new Get(
uriTemplate: '/{id}',
requirements: ['id' => 'd+']
),
new GetCollection(
uriTemplate: '/categories/{categoryId}',
provider: ArticlesByCategoryProvider::class
)
],
routePrefix: '/articles',
normalizationContext: ['groups' => ['articles_read']],
denormalizationContext: ['groups' => ['articles_write']]
)]
class Article
{
#[ORMId]
#[ORMGeneratedValue]
#[ORMColumn]
#[Groups(['articles_read'])]
private ?int $id = null;
#[ORMColumn(length: 255)]
#[Groups(['articles_read', 'articles_write'])]
private ?string $title = null;
#[ORMColumn(type: 'text')]
#[Groups(['articles_read', 'articles_write'])]
private ?string $content = null;
#[ORMManyToOne(targetEntity: Category::class)]
#[ORMJoinColumn(nullable: false)]
#[Groups(['articles_read', 'articles_write'])]
private ?Category $category = null;
// Other fields and methods...
}
The issue
When I try to access /api/articles/categories/{categoryId}, it seems that API Platform tries to resolve {categoryId} as if it were an id for the Article entity itself, leading to this error :
“Invalid identifier value or configuration.”
I was able to solve my problem by putting /categories/{id}, but I would like to know if we can get around that, knowing that I can have several entities in the url, for example /categories/{categoryId}/tags/{tagId}.
Questions
- Why does API Platform enforce using {id}?
- Is there a way to use a different parameter like {categoryId} in the uriTemplate?
- How can I configure my routes and providers to work with a parameter other than {id}?
Any insights or examples would be greatly appreciated!
Thank you!