main Resource Polymorphism

Since API Platform 5.1, a resource can expose several subtypes. The subtypes are declared in a Symfony Serializer #[DiscriminatorMap] on the resource class. API Platform then reads, writes and documents the properties of each subtype on the endpoints of the resource.

# Enabling Polymorphism

Polymorphism is off by default. Enable it with the discriminator_map option.

# api/config/packages/api_platform.yaml
api_platform:
    serializer:
        discriminator_map: true
<?php
// config/api-platform.php
return [
    // ...
    'serializer' => [
        'discriminator_map' => true,
    ],
];

# Declaring the Subtypes

Declare the #[DiscriminatorMap] on the resource. API Platform only reads the map you declare: it does not derive subtypes from the Doctrine inheritance mapping.

<?php
// api/src/ApiResource/Vehicle.php with Symfony or app/ApiResource/Vehicle.php with Laravel
namespace App\ApiResource;

use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Metadata\Get;
use ApiPlatform\Metadata\GetCollection;
use ApiPlatform\Metadata\Patch;
use ApiPlatform\Metadata\Post;
use Symfony\Component\Serializer\Attribute\DiscriminatorMap;

#[ApiResource(operations: [new GetCollection(), new Get(), new Post(), new Patch()])]
#[DiscriminatorMap(typeProperty: 'kind', mapping: [
    'car' => Car::class,
    'truck' => Truck::class,
])]
abstract class Vehicle
{
    public ?int $id = null;

    public string $name = '';
}
<?php
// api/src/ApiResource/Truck.php with Symfony or app/ApiResource/Truck.php with Laravel
namespace App\ApiResource;

final class Truck extends Vehicle
{
    public ?int $payload = null;
}

The type property (kind here) does not need to exist on the class.

A subtype does not have to be a resource. A subtype that is not a resource is named after its class short name in JSON-LD and Hydra (Truck). Declare it as a resource, for example with #[ApiResource(operations: [])], to give it another name or types.

# Reading and Writing Subtypes

Every format that supports the object (JSON-LD, Hydra, HAL, JSON:API and plain JSON) exposes the properties of the subtype next to the properties of the root resource:

{
    "@context": "/contexts/Vehicle",
    "@id": "/vehicles/2",
    "@type": "Truck",
    "kind": "truck",
    "name": "Actros",
    "payload": 18000
}

On a POST, API Platform reads the type property and creates the most specific subtype. A subclass that is not in the map is exposed as its closest mapped parent. Subtype properties can override the inherited ones: their ApiProperty metadata and validation constraints are enforced on write.

An update never changes the subtype:

  • A PUT or a PATCH whose type property names another subtype returns a 422 response.
  • A JSON-LD @type that contradicts the type property returns a 422 response.
  • A PUT without the type property keeps the current subtype.

# Security


Operations, and therefore their security expressions, are taken from the root resource only. A subtype does not get its own security.

The operation that handles a request is the one matching the URL. On the endpoints of the root resource (/vehicles), security, securityPostDenormalize and the other operation options of the root apply to every subtype. A subtype that you also declare as a resource has its own operations, but they only apply on its own endpoints: a PATCH /vehicles/6 on a bus still uses the operations of Vehicle, not the ones of Bus.

Restrict the root operations accordingly, and do not rely on a subtype security option to protect data on the root endpoints.

Property-level security declared with #[ApiProperty(security: ...)] on a subtype property is applied for each user:

<?php
// api/src/ApiResource/Truck.php with Symfony or app/ApiResource/Truck.php with Laravel
namespace App\ApiResource;

use ApiPlatform\Metadata\ApiProperty;

final class Truck extends Vehicle
{
    #[ApiProperty(security: "is_granted('ROLE_ADMIN')")]
    public ?string $plate = null;

    public ?int $payload = null;
}

# JSON Schema and OpenAPI

A class with a discriminator map is documented as a oneOf of its subtypes. In the OpenAPI document, the schema also carries a discriminator that maps each type value to its subtype:

{
    "oneOf": [{ "$ref": "#/components/schemas/Car" }, { "$ref": "#/components/schemas/Truck" }],
    "discriminator": {
        "propertyName": "kind",
        "mapping": {
            "car": "#/components/schemas/Car",
            "truck": "#/components/schemas/Truck"
        }
    }
}

The plain JSON Schema has the oneOf and no discriminator, as the keyword is specific to OpenAPI. Hydra documents the subtypes as subclasses of the root class.

The oneOf applies to resources only when discriminator_map is enabled. A class that is not a resource, such as an input DTO, is always documented that way, and its payload is denormalized to the subtype named by the type property.

# GraphQL

GraphQL does not support polymorphic resources yet. The default GraphQL operations of a resource with a discriminator map are dropped, while relations that point to it still resolve. Explicit graphQlOperations on such a resource throw an exception: remove them or set them to an empty array.

You can also help us improve the documentation of this page.

Using an AI coding agent? See the documentation index for LLMs at /docs/llms.txt.

Made with love by

Les-Tilleuls.coop can help you design and develop your APIs and web projects, and train your teams in API Platform, Symfony, Next.js, Kubernetes and a wide range of other technologies.

Learn more

Copyright © 2023 Kévin Dunglas

Sponsored by Les-Tilleuls.coop