API Platform and Doctrine¶
The combination of API Platform and Doctrine is a powerful tool for building APIs. API Platform has a built-in support for Doctrine entities. This means that you can use your existing Doctrine entities as the base of your API.
Creating a new API endpoint is as simple as creating a new Doctrine entity and annotating it with the ApiResource attribute.
If not specified otherwise, API Platform will automatically create CRUD operations for the entity.
Each endpoint can be customized. For example, you can add custom operations, change the serialization groups, or restrict access. This can be done by adding the necessary attributes to the entity.
Example¶
The following example shows how to create a new API endpoint for a Environment entity:
<?php
namespace App\Entity;
use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Metadata\Delete;
use ApiPlatform\Metadata\Get;
use ApiPlatform\Metadata\GetCollection;
use ApiPlatform\Metadata\Post;
use ApiPlatform\Metadata\Put;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Serializer\Annotation\Groups;
#[ORM\Entity()]
#[ApiResource(
operations: [
new GetCollection(
uriTemplate: '/environments',
normalizationContext: ['groups' => ['collection'], 'skip_null_values' => false]
),
new Get(
uriTemplate: '/environments/{id}',
normalizationContext: ['groups' => ['detail'], 'skip_null_values' => false]
),
new Post(
uriTemplate: '/environments',
security: "is_granted('ROLE_ADMINISTRATOR')",
securityMessage: "Access Denied: You don't have the rights to perform the action."
),
new Put(
uriTemplate: '/environments/{id}',
security: "is_granted('ROLE_ADMINISTRATOR')",
securityMessage: "Access Denied: You don't have the rights to perform the action."
),
new Delete(
uriTemplate: '/environments/{id}',
security: "is_granted('ROLE_ADMINISTRATOR')",
securityMessage: "Access Denied: You don't have the rights to perform the action."
),
]
)]
class Environment
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column(type: "integer")]
#[Groups(['collection', 'export'])]
private ?int $id = null;
#[ORM\Column(type: "string", length: 255)]
#[Groups(['collection', 'detail', 'export'])]
private ?string $name = null;
// ...
}
This is a simple example exposing the doctrine entity Environment as an API endpoint. The entity has a few properties
(id and name) and is annotated with the ApiResource attribute. The attribute contains several operations: GetCollection,
Get, Post, Put, and Delete. Each operation has a specific URI template and security settings.
Also, you can see a serilization group Groups which is used to control which properties are serialized in the response.
If an environment is requested as a collection, detail or export, the id and name properties are serialized.