Skip to content
Tutorials Center
My learning

Topics

Lesson 51 of 62 ยท APIs

API Platform Overview

A tour of API Platform on Symfony: declare a resource, get CRUD operations, filters, pagination and OpenAPI docs, and see the idea in a runnable stand-in.

In the previous lessons you wrote each endpoint yourself: a route, a controller method, pagination, error handling, serialization. Most APIs repeat the same patterns for every entity, which makes them a good target for automation. API Platform is a framework built on top of Symfony that generates a full REST (or GraphQL) API from a description of your resources, together with machine-readable documentation.

You do not need it for every project. A handful of hand-written endpoints is often clearer. But once you have ten or twenty resources with filtering, pagination and documentation requirements, writing it all by hand becomes expensive. This lesson explains what API Platform gives you, how to declare a resource, and what the generated machinery does. API Platform needs Composer packages and a web server, so every API Platform snippet is read-only here, and the runnable examples are plain-PHP stand-ins of the idea.

What you get

Install it in a Symfony project with composer require api. From a few attributes on a class, API Platform provides:

  • Routes and operations for listing, reading, creating, replacing, patching and deleting a resource.
  • Serialization through the Serializer, including groups, and content negotiation (JSON-LD, JSON, and others).
  • Validation through the Validator, with errors returned as structured responses (422).
  • Pagination, with sensible defaults, for every collection.
  • Filters for searching and sorting by query parameters.
  • Documentation: an OpenAPI description of the API and an interactive docs page, generated from your code.
flowchart TB
    R["Resource class<br/>(#[ApiResource])"] --> O["Operations<br/>GET, POST, PATCH, DELETE"]
    O --> P["State provider<br/>(reads data)"]
    O --> S["State processor<br/>(writes data)"]
    O --> SZ["Serializer and Validator"]
    R --> D["OpenAPI document and docs UI"]
    P --> DB["Doctrine or any data source"]
    S --> DB

One resource declaration feeds operations, data access, serialization and documentation.

Declaring a resource

The simplest start is an entity with one attribute:

PHP
// src/Entity/Book.php (real API Platform, read-only)
namespace App\Entity;

use ApiPlatform\Metadata\ApiResource;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

#[ORM\Entity]
#[ApiResource]
class Book
{
    #[ORM\Id, ORM\GeneratedValue, ORM\Column]
    private ?int $id = null;

    #[ORM\Column]
    #[Assert\NotBlank]
    private string $title = '';

    #[ORM\Column]
    private string $author = '';

    // getters and setters ...
}

With no further configuration, this one attribute exposes GET /api/books, POST /api/books, GET /api/books/{id}, PUT, PATCH and DELETE, plus an OpenAPI document and a docs page. Validation runs on writes, and the constraints appear in the documentation.

You control what is exposed by listing operations explicitly, and you control the data shape with serialization groups:

PHP
// real API Platform, read-only
use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Metadata\Get;
use ApiPlatform\Metadata\GetCollection;
use ApiPlatform\Metadata\Post;

#[ApiResource(
    operations: [
        new GetCollection(),
        new Get(),
        new Post(security: "is_granted('ROLE_ADMIN')"),
    ],
    normalizationContext: ['groups' => ['book:read']],
    denormalizationContext: ['groups' => ['book:write']],
    paginationItemsPerPage: 20,
)]
class Book
{
    // ...
}

Here only listing, reading and creating exist; there is no DELETE route at all. Creating needs the admin role through the security expression (see authorization). The read and write groups reuse the naming convention from the serializer lesson.

Exposing a Doctrine entity directly couples your public API to your database schema. It is fast to start, but renaming a column becomes a breaking API change. For long-lived APIs, declare the resource on a separate DTO class and map it from the entity with a state provider.

Filters

Collections become useful when clients can narrow them down. Filters are declared with attributes, either on the class or on a property:

PHP
// real API Platform, read-only
use ApiPlatform\Doctrine\Orm\Filter\OrderFilter;
use ApiPlatform\Doctrine\Orm\Filter\SearchFilter;
use ApiPlatform\Metadata\ApiFilter;

#[ApiResource]
#[ApiFilter(SearchFilter::class, properties: ['author' => 'partial', 'title' => 'ipartial'])]
#[ApiFilter(OrderFilter::class, properties: ['title', 'id'])]
class Book
{
    // ...
}

That makes GET /api/books?author=orw search authors containing "orw" and GET /api/books?order[title]=asc sort by title. There are also filters for dates, ranges, booleans and existence checks. Newer API Platform versions also let you attach filters per operation and offer a property-based #[QueryParameter] syntax; check the version you install, because the exact attribute names have evolved. Filters work on the query builder, so the database does the filtering and pagination, never PHP.

State providers and processors

API Platform separates reading from writing with two small interfaces:

  • A state provider receives the operation and its URL variables and returns the data: one object, or a paginated collection.
  • A state processor receives the data of a write operation and persists it, sends it on, or does anything else.

With Doctrine installed, the default provider and processor read and write entities. When your data lives somewhere else (another API, a file, a computed result), you write your own:

PHP
// src/State/BookProvider.php (real API Platform, read-only)
namespace App\State;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProviderInterface;

final class BookProvider implements ProviderInterface
{
    public function provide(Operation $operation, array $uriVariables = [], array $context = []): object|array|null
    {
        // return one resource, a list, or null (which becomes a 404)
    }
}

You attach it with provider: BookProvider::class on the resource or an individual operation. A processor works the same way with a process() method, and it is the right place for side effects such as hashing a password or dispatching a Messenger message.

OpenAPI documentation

Every operation, filter, validation constraint and serialization group feeds an OpenAPI document (the standard JSON description of an HTTP API, formerly called Swagger). API Platform serves it at /api/docs.json (or .jsonopenapi), and an interactive page at /api/docs lets you try each request in the browser. Client generators and API gateways can consume the same document, so you rarely have to write documentation by hand, and it cannot drift from the code.

You can still enrich it with openapi: options on operations (descriptions, examples), and you can decorate the documentation service to add global information.

A stand-in: from one declaration to many endpoints

The real component generates its routes by reading metadata from attributes. The stand-in below does the same at toy scale: a resource class carries an attribute that lists its operations, and a small function turns that metadata into a route table.

PHP Generating routes from resource metadata (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The Book class declares nothing and receives all five operations; Author limits itself to two and uses a custom path. That is the essence of the framework: metadata in, routes out. The real thing adds serialization, validation, pagination and documentation to every generated operation.

A stand-in: filters and pagination

Filters turn query parameters into a narrowed, ordered, paged result. The stand-in applies the same three ideas to an in-memory array.

PHP Query-parameter filters and pagination (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Notice the allow-lists inside the function: only title and author can be searched, only title and id can be sorted. In API Platform, a filter attribute is that allow-list; a client cannot sort by a column you did not declare.

When to choose API Platform

  • Choose it for CRUD-heavy APIs with many resources, when you want OpenAPI and an admin-style docs page out of the box, or when you want a client such as a JavaScript front end to discover the API from its own description.
  • Skip it for a few bespoke endpoints, for strongly action-oriented APIs ("approve order", "send reminder") where CRUD mapping fights you, or when the team wants every line of the HTTP layer explicit. Plain controllers with #[MapRequestPayload] are perfectly professional.

You can also mix: API Platform for the CRUD resources, normal Symfony controllers for the special endpoints.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does adding #[ApiResource] to an entity do in API Platform?

    From that one attribute API Platform builds the CRUD routes and wires in the serializer, validator, pagination and OpenAPI documentation.
  2. 2. What is the role of a state provider?

    Providers read data, processors write it. With Doctrine the defaults do this for you; custom ones let you use any data source.
  3. 3. Why can exposing Doctrine entities directly be risky for a long-lived API?

    A DTO resource decouples the public contract from storage, so you can refactor tables without breaking clients.
  4. 4. Where does the OpenAPI documentation come from?

    API Platform builds the OpenAPI document from your code, so it stays in sync with what the API actually does.

Summary

  • API Platform sits on Symfony and generates REST (and GraphQL) APIs from resource declarations.
  • #[ApiResource] plus optional operations gives you routes, serialization, validation, pagination and an OpenAPI document.
  • Filters are declared with attributes and run in the database; they act as allow-lists for searching and sorting.
  • State providers read and processors write data, so any data source can back a resource.
  • Prefer DTO resources for long-lived public APIs; mix API Platform with plain controllers where CRUD does not fit.
  • API Platform code is read-only on this site; the runnable examples are plain-PHP stand-ins.

Next up: HTTP Caching.