Guides Declare a Resource
Guide

Declare a Resource

design
This class represents an API resource
// src/App/ApiResource.php
namespace App\ApiResource;
The #[ApiResource] attribute registers this class as an HTTP resource.
use ApiPlatform\Metadata\ApiResource;
These are the list of HTTP operations we use to declare a “CRUD” (Create, Read, Update, Delete).
use ApiPlatform\Metadata\Delete;
use ApiPlatform\Metadata\Get;
use ApiPlatform\Metadata\GetCollection;
use ApiPlatform\Metadata\Patch;
use ApiPlatform\Metadata\Post;
use ApiPlatform\Validator\Exception\ValidationException;
Each resource has its set of Operations. Note that the uriTemplate may use the id variable which is our unique identifier on this Book.
#[ApiResource(
    operations: [
        new Get(uriTemplate: '/books/{id}'),
The GetCollection operation returns a list of Books.
        new GetCollection(uriTemplate: '/books'),
        new Post(uriTemplate: '/books'),
        new Patch(uriTemplate: '/books/{id}'),
        new Delete(uriTemplate: '/books/{id}'),
    ],
This is a configuration that is shared accross every operations. More details are available at ApiResource::exceptionToStatus.
    exceptionToStatus: [
        ValidationException::class => 422,
    ]
)]
If a property named id is found it is the property used in your URI template we recommend to use public properties to declare API resources.
class Book
{
    public string $id;
}
Check our next guide to provide the resource state.
// src/App/Playground.php
namespace App\Playground;
use Symfony\Component\HttpFoundation\Request;
function request(): Request
{
    return Request::create('/docs', 'GET');
}

You can also help us improve this guide.

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