Magento 2 Experten — Hyvä Theme, Tailwind CSS & SEO aus einer Hand ›

Serialisierungsgruppen für das Lesen

Serialisierungsgruppen für das Lesen

~15 Min. Lesezeit Zuletzt aktualisiert am 8. August 2026

Bisher erscheinen ALLE Properties einer Entity im JSON – normalizationContext mit Serialisierungsgruppen erlaubt es, das GEZIELT einzuschränken.

Das #[Groups]-Attribut auf Properties

api/src/Entity/Project.php
use ApiPlatform\Metadata\ApiResource;
use Symfony\Component\Serializer\Attribute\Groups;

#[ApiResource(
    normalizationContext: ['groups' => ['project:read']]
)]
#[ORM\Entity(repositoryClass: ProjectRepository::class)]
class Project
{
    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column]
    #[Groups(['project:read'])]
    private ?int $id = null;

    #[ORM\Column(length: 255)]
    #[Assert\NotBlank]
    #[Groups(['project:read'])]
    private string $name = '';

    #[ORM\Column(type: 'text', nullable: true)]
    #[Groups(['project:read'])]
    private ?string $description = null;

    #[ORM\Column]
    #[Groups(['project:read'])]
    private \DateTimeImmutable $createdAt;

    // priority OHNE #[Groups] - erscheint dadurch NICHT mehr im JSON
    #[ORM\Column]
    #[Assert\Range(min: 1, max: 5)]
    private int $priority = 3;

    // ... Getter/Setter unverändert
}

normalizationContext steuert das LESEN (GET-Antworten) – NUR Properties mit #[Groups(['project:read'])] landen im Antwort-JSON.

Das Ergebnis prüfen

curl -k https://localhost/api/projects/1
{
  "@context": "/api/contexts/Project",
  "@id": "/api/projects/1",
  "@type": "Project",
  "id": 1,
  "name": "Website-Relaunch",
  "description": "Kompletter Redesign",
  "createdAt": "2026-08-06T12:00:00+00:00"
}

Achtung: priority FEHLT KOMPLETT in der Antwort, OBWOHL das Feld in der Datenbank existiert und einen Wert hat – Serialisierungsgruppen filtern NICHT einzelne Werte, sondern ganze Properties AUS der Antwort HERAUS.

Gruppen auf mehrere Resources anwenden

GENAU dasselbe Attribut kommt auch bei Tag zum Einsatz – #[Groups(['tag:read'])] auf id und name, mit EIGENEM, unabhängigem Gruppennamen. Gruppennamen sind FREI wählbar, es gibt KEINE technische Vorgabe für {resource}:{zweck} außer der GUTEN Lesbarkeit.

Tipp: Fehlt normalizationContext KOMPLETT (wie bisher in Kapitel 9-22), wirken KEINE Gruppen-Filter – ALLE Properties erscheinen automatisch. Der Umstieg auf explizite Gruppen ist ein BEWUSSTER Schritt, kein automatisches Verhalten.