Symfony 7: API Platform und Best Practices
Vollstaendiger Leitfaden zur Erstellung professioneller REST-APIs mit Symfony 7 und API Platform 4. State Providers, Processors, Validierung und Serialisierung erklaert.

API Platform 4 transformiert die Erstellung von REST- und GraphQL-APIs mit Symfony. Version 4.4, veroeffentlicht im September 2026, bringt komponierbare Filter, veraltete #[ApiFilter]-Dekoratoren und native OpenAPI 3.2-Unterstuetzung. Kombiniert mit Symfonys Service Container und Autowiring wird die Erstellung einer professionellen API unkompliziert.
Version 4.4 markiert die veralteten #[ApiFilter]-Dekoratoren als deprecated (Entfernung geplant fuer 6.0) zugunsten komponierbarer Filter wie ComparisonFilter, OrFilter und ChainFilter. Scalar UI ersetzt Swagger UI als Standard seit 4.3, und OpenAPI 3.2 wird vollstaendig unterstuetzt. Siehe die offiziellen Release Notes fuer Migrationshinweise.
Installation und Erstkonfiguration
API Platform wird mit wenigen Befehlen ueber Symfony Flex installiert. Die Standardkonfiguration deckt die meisten Anwendungsfaelle ab und bleibt vollstaendig anpassbar.
# terminal
# Create a new Symfony project with API Platform
composer create-project symfony/skeleton my-api
cd my-api
# Install API Platform with Doctrine ORM
composer require api
# Verify installation
php bin/console debug:router | grep apiSymfony Flex konfiguriert automatisch Routen, OpenAPI-Dokumentation und die Scalar UI-Oberflaeche unter /api. Die API Platform Dokumentation behandelt alle Konfigurationsoptionen.
# config/packages/api_platform.yaml
api_platform:
title: 'My API'
version: '1.0.0'
# Supported response formats
formats:
jsonld: ['application/ld+json']
json: ['application/json']
# OpenAPI documentation
swagger:
versions: [3]
# Default pagination
defaults:
pagination_items_per_page: 30
pagination_maximum_items_per_page: 100Diese Konfiguration definiert Serialisierungsformate, globale Paginierung und API-Dokumentationsmetadaten.
Erstellen einer einfachen API-Ressource
Das #[ApiResource]-Attribut stellt eine Doctrine-Entitaet als REST-Ressource bereit. API Platform generiert automatisch CRUD-Endpunkte, OpenAPI-Dokumentation und grundlegende Validierungen.
<?php
// src/Entity/Book.php
namespace App\Entity;
use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Metadata\Get;
use ApiPlatform\Metadata\GetCollection;
use ApiPlatform\Metadata\Post;
use ApiPlatform\Metadata\Put;
use ApiPlatform\Metadata\Patch;
use ApiPlatform\Metadata\Delete;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
#[ORM\Entity]
#[ApiResource(
// Explicit definition of available operations
operations: [
new GetCollection(),
new Post(),
new Get(),
new Put(),
new Patch(),
new Delete(),
],
// Default ordering for collections
order: ['publishedAt' => 'DESC'],
// Pagination configuration for this resource
paginationItemsPerPage: 20
)]
class Book
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int = null;
#[ORM\Column(length: 255)]
#[Assert\NotBlank(message: 'Title is required')]
#[Assert\Length(min: 2, max: 255)]
private ?string = null;
#[ORM\Column(type: 'text')]
#[Assert\NotBlank]
private ?string = null;
#[ORM\Column(length: 13, unique: true)]
#[Assert\Isbn]
private ?string = null;
#[ORM\Column]
private ?\DateTimeImmutable = null;
// Getters and setters...
public function getId(): ?int
{
return ->id;
}
public function getTitle(): ?string
{
return ->title;
}
public function setTitle(string ): static
{
->title = ;
return ;
}
public function getDescription(): ?string
{
return ->description;
}
public function setDescription(string ): static
{
->description = ;
return ;
}
public function getIsbn(): ?string
{
return ->isbn;
}
public function setIsbn(string ): static
{
->isbn = ;
return ;
}
public function getPublishedAt(): ?\DateTimeImmutable
{
return ->publishedAt;
}
public function setPublishedAt(\DateTimeImmutable ): static
{
->publishedAt = ;
return ;
}
}Diese Entitaet generiert sechs Endpunkte: GET /api/books, POST /api/books, GET /api/books/{id}, PUT /api/books/{id}, PATCH /api/books/{id} und DELETE /api/books/{id}.
API Platform unterstuetzt UUID v7 nativ als Identifikatoren. Dieser Ansatz verbessert die Sicherheit (nicht vorhersagbare Identifikatoren) und die Performance (natuerliche Sortierung nach Erstellungsdatum).
Serialisierungsgruppen zur Kontrolle exponierter Daten
Serialisierungsgruppen definieren praezise, welche Eigenschaften beim Lesen (Normalisierung) und Schreiben (Denormalisierung) exponiert werden. Diese Trennung ist essentiell fuer die Sicherheit und Flexibilitaet der API. Fuer komplexe Serialisierungsszenarien bietet die Symfony Serializer Komponente zusaetzliche Anpassungsmoeglichkeiten.
<?php
// src/Entity/User.php
namespace App\Entity;
use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Metadata\Get;
use ApiPlatform\Metadata\GetCollection;
use ApiPlatform\Metadata\Post;
use ApiPlatform\Metadata\Put;
use ApiPlatform\Metadata\Patch;
use ApiPlatform\Metadata\Delete;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Serializer\Annotation\Groups;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use App\State\UserPasswordHasher;
#[ORM\Entity]
#[ORM\Table(name: '`user`')]
#[UniqueEntity('email')]
#[ApiResource(
operations: [
new GetCollection(),
// Custom processor for password hashing
new Post(processor: UserPasswordHasher::class,
validationContext: ['groups' => ['Default', 'user:create']]),
new Get(),
new Put(processor: UserPasswordHasher::class),
new Patch(processor: UserPasswordHasher::class),
new Delete(),
],
// Properties exposed when reading
normalizationContext: ['groups' => ['user:read']],
// Properties accepted when writing
denormalizationContext: ['groups' => ['user:create', 'user:update']],
)]
class User implements UserInterface, PasswordAuthenticatedUserInterface
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
#[Groups(['user:read'])]
private ?int = null;
#[ORM\Column(length: 180, unique: true)]
#[Assert\NotBlank]
#[Assert\Email]
#[Groups(['user:read', 'user:create', 'user:update'])]
private ?string = null;
#[ORM\Column]
private ?string = null;
// Never exposed when reading, only when writing
#[Assert\NotBlank(groups: ['user:create'])]
#[Groups(['user:create', 'user:update'])]
private ?string = null;
#[ORM\Column(length: 100)]
#[Groups(['user:read', 'user:create', 'user:update'])]
private ?string = null;
#[ORM\Column(type: 'json')]
#[Groups(['user:read'])]
private array = [];
#[ORM\Column]
#[Groups(['user:read'])]
private ?\DateTimeImmutable = null;
public function __construct()
{
->createdAt = new \DateTimeImmutable();
}
// UserInterface implementation
public function getUserIdentifier(): string
{
return (string) ->email;
}
public function getRoles(): array
{
= ->roles;
[] = 'ROLE_USER';
return array_unique();
}
public function getPassword(): string
{
return ->password;
}
public function eraseCredentials(): void
{
->plainPassword = null;
}
// Getters and setters...
public function getId(): ?int
{
return ->id;
}
public function getEmail(): ?string
{
return ->email;
}
public function setEmail(string ): static
{
->email = ;
return ;
}
public function setPassword(string ): static
{
->password = ;
return ;
}
public function getPlainPassword(): ?string
{
return ->plainPassword;
}
public function setPlainPassword(?string ): static
{
->plainPassword = ;
return ;
}
public function getFullName(): ?string
{
return ->fullName;
}
public function setFullName(string ): static
{
->fullName = ;
return ;
}
public function setRoles(array ): static
{
->roles = ;
return ;
}
public function getCreatedAt(): ?\DateTimeImmutable
{
return ->createdAt;
}
}Mit dieser Konfiguration wird plainPassword niemals in Antworten exponiert, kann aber bei Erstellung oder Aktualisierung gesendet werden.
Bereit für deine Symfony-Interviews?
Übe mit unseren interaktiven Simulatoren, Flashcards und technischen Tests.
State Processors fuer Geschaeftslogik
State Processors fangen Persistenzoperationen ab, um Geschaeftslogik hinzuzufuegen. API Platform vereinfacht ihre Erstellung durch attributbasierte Dependency Injection.
<?php
// src/State/UserPasswordHasher.php
namespace App\State;
use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProcessorInterface;
use App\Entity\User;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
/**
* Processor that hashes password before persistence
* @implements ProcessorInterface<User, User>
*/
final class UserPasswordHasher implements ProcessorInterface
{
public function __construct(
// Injection of standard Doctrine processor
#[Autowire(service: 'api_platform.doctrine.orm.state.persist_processor')]
private ProcessorInterface ,
private UserPasswordHasherInterface ,
) {
}
public function process(mixed , Operation , array = [], array = []): User
{
// Hash password if provided
if (->getPlainPassword()) {
= ->passwordHasher->hashPassword(
,
->getPlainPassword()
);
->setPassword();
->eraseCredentials();
}
// Delegate persistence to standard processor
return ->persistProcessor->process(, , , );
}
}Dieses Kompositionsmuster ermoeglicht das Hinzufuegen beliebiger Logik (E-Mail-Versand, Events, Logging) bei Beibehaltung des Standard-Persistenzverhaltens. Fuer ereignisgesteuerte Architekturen arbeiten Processors nahtlos mit Symfony Messenger zusammen.
Processor mit bedingter Logik
Ein Processor kann sein Verhalten je nach Operationstyp anpassen.
<?php
// src/State/BookProcessor.php
namespace App\State;
use ApiPlatform\Metadata\DeleteOperationInterface;
use ApiPlatform\Metadata\Operation;
use ApiPlatform\Metadata\Post;
use ApiPlatform\State\ProcessorInterface;
use App\Entity\Book;
use App\Service\NotificationService;
use App\Service\SearchIndexer;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
/**
* @implements ProcessorInterface<Book, Book|void>
*/
final class BookProcessor implements ProcessorInterface
{
public function __construct(
#[Autowire(service: 'api_platform.doctrine.orm.state.persist_processor')]
private ProcessorInterface ,
#[Autowire(service: 'api_platform.doctrine.orm.state.remove_processor')]
private ProcessorInterface ,
private NotificationService ,
private SearchIndexer ,
) {
}
public function process(mixed , Operation , array = [], array = []): mixed
{
// Deletion: use remove processor
if ( instanceof DeleteOperationInterface) {
->searchIndexer->remove();
return ->removeProcessor->process(, , , );
}
// Creation: set publication date
if ( instanceof Post) {
->setPublishedAt(new \DateTimeImmutable());
}
// Standard persistence
= ->persistProcessor->process(, , , );
// Post-processing: indexing and notification
->searchIndexer->index();
if ( instanceof Post) {
->notifications->notifyNewBook();
}
return ;
}
}State Providers fuer benutzerdefinierte Datenquellen
State Providers holen Daten aus beliebigen Quellen: externe APIs, Cache, Dateien oder komplexe Geschaeftslogik.
<?php
// src/State/PopularBooksProvider.php
namespace App\State;
use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProviderInterface;
use App\Entity\Book;
use App\Repository\BookRepository;
use Symfony\Contracts\Cache\CacheInterface;
use Symfony\Contracts\Cache\ItemInterface;
/**
* Provider that returns popular books with caching
* @implements ProviderInterface<Book>
*/
final class PopularBooksProvider implements ProviderInterface
{
public function __construct(
private BookRepository ,
private CacheInterface ,
) {
}
public function provide(Operation , array = [], array = []): array
{
// 5-minute cache for popular books
return ->cache->get('popular_books', function (ItemInterface ) {
->expiresAfter(300);
return ->bookRepository->findPopular(limit: 10);
});
}
}Dieser Provider wird auf einer dedizierten Operation verwendet.
<?php
// src/Entity/Book.php (excerpt)
use App\State\PopularBooksProvider;
#[ApiResource(
operations: [
// ... other operations
new GetCollection(
uriTemplate: '/books/popular',
provider: PopularBooksProvider::class,
paginationEnabled: false,
),
],
)]
class Book
{
// ...
}Erweiterte Validierung mit dynamischen Gruppen
API Platform integriert nativ Symfonys Validator-Komponente. Validierungsgruppen koennen je nach Operation oder Kontext variieren.
<?php
// src/Entity/Article.php
namespace App\Entity;
use ApiPlatform\Metadata\ApiResource;
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\Validator\Constraints as Assert;
#[ORM\Entity]
#[ApiResource(
operations: [
new GetCollection(),
new Get(),
// Strict validation on creation
new Post(validationContext: ['groups' => ['Default', 'article:create']]),
// More lenient validation for updates
new Put(validationContext: ['groups' => ['Default', 'article:update']]),
],
)]
class Article
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int = null;
#[ORM\Column(length: 255)]
#[Assert\NotBlank]
#[Assert\Length(min: 10, max: 255)]
private ?string = null;
#[ORM\Column(type: 'text')]
#[Assert\NotBlank]
// Minimum 500 characters on creation
#[Assert\Length(min: 500, groups: ['article:create'])]
// Minimum 100 characters for updates
#[Assert\Length(min: 100, groups: ['article:update'])]
private ?string = null;
#[ORM\Column(length: 50)]
#[Assert\NotBlank(groups: ['article:create'])]
#[Assert\Choice(choices: ['draft', 'published', 'archived'])]
private ?string = 'draft';
#[ORM\Column(nullable: true)]
// Required only if status is "published"
#[Assert\NotBlank(groups: ['article:publish'])]
private ?\DateTimeImmutable = null;
// Getters and setters...
}Dynamische Validierung mit einem Service
Fuer komplexe Validierungsregeln bietet ein benutzerdefinierter Gruppengenerator maximale Flexibilitaet.
<?php
// src/Validator/ArticleGroupsGenerator.php
namespace App\Validator;
use ApiPlatform\Symfony\Validator\ValidationGroupsGeneratorInterface;
use App\Entity\Article;
use Symfony\Bundle\SecurityBundle\Security;
final class ArticleGroupsGenerator implements ValidationGroupsGeneratorInterface
{
public function __construct(
private Security ,
) {
}
public function __invoke(object ): array
{
assert( instanceof Article);
= ['Default'];
// Admins have fewer restrictions
if (->security->isGranted('ROLE_ADMIN')) {
[] = 'admin';
return ;
}
// Additional validation if publishing
if (->getStatus() === 'published') {
[] = 'article:publish';
}
return ;
}
}Komplexe Validierungen koennen die Performance beeintraechtigen. Bei Massenimporten ist zu erwaegen, bestimmte Validierungen voruebergehend zu deaktivieren oder asynchrone Constraints zu verwenden.
Filter fuer flexible Abfragen
API Platform 4.4 ueberarbeitet das Filtersystem mit komponierbaren Filtern. Der veraltete #[ApiFilter]-Dekorator ist deprecated (Entfernung geplant fuer 6.0), und ein Codemod ist fuer die Migration verfuegbar.
<?php
// src/Entity/Product.php
namespace App\Entity;
use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Metadata\ApiFilter;
use ApiPlatform\Doctrine\Orm\Filter\SearchFilter;
use ApiPlatform\Doctrine\Orm\Filter\RangeFilter;
use ApiPlatform\Doctrine\Orm\Filter\OrderFilter;
use ApiPlatform\Doctrine\Orm\Filter\BooleanFilter;
use ApiPlatform\Doctrine\Orm\Filter\DateFilter;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity]
#[ApiResource]
// Text search on name and description
#[ApiFilter(SearchFilter::class, properties: [
'name' => 'partial', // LIKE %value%
'description' => 'partial',
'category.name' => 'exact', // Search on relation
'sku' => 'exact', // Exact match
])]
// Range filtering
#[ApiFilter(RangeFilter::class, properties: ['price', 'stock'])]
// Date filtering
#[ApiFilter(DateFilter::class, properties: ['createdAt', 'updatedAt'])]
// Boolean filtering
#[ApiFilter(BooleanFilter::class, properties: ['isActive', 'isFeatured'])]
// Customizable sorting
#[ApiFilter(OrderFilter::class, properties: [
'name',
'price',
'createdAt',
], arguments: ['orderParameterName' => 'sort'])]
class Product
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int = null;
#[ORM\Column(length: 255)]
private ?string = null;
#[ORM\Column(type: 'text', nullable: true)]
private ?string = null;
#[ORM\Column(length: 50, unique: true)]
private ?string = null;
#[ORM\Column(type: 'decimal', precision: 10, scale: 2)]
private ?string = null;
#[ORM\Column]
private ?int = null;
#[ORM\Column]
private ?bool = true;
#[ORM\Column]
private ?bool = false;
#[ORM\ManyToOne(targetEntity: Category::class)]
private ?Category = null;
#[ORM\Column]
private ?\DateTimeImmutable = null;
#[ORM\Column(nullable: true)]
private ?\DateTimeImmutable = null;
// Getters and setters...
}Diese Filter generieren automatisch OpenAPI-Dokumentation und ermoeglichen Abfragen wie:
GET /api/products?name=phone&price[gte]=100&price[lte]=500&isActive=true&sort[price]=ascAPI Platform 4.4 fuehrt neue Filter ein: StartSearchFilter, EndSearchFilter, WordStartSearchFilter sowie komponierbare Wrapper wie ComparisonFilter, OrFilter und ChainFilter.
Beziehungen und Subressourcen
API Platform behandelt Entitaetsbeziehungen elegant mit Serialisierungsoptionen und Subressourcen.
<?php
// src/Entity/Author.php
namespace App\Entity;
use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Metadata\Get;
use ApiPlatform\Metadata\GetCollection;
use ApiPlatform\Metadata\Link;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Serializer\Annotation\Groups;
#[ORM\Entity]
#[ApiResource(
normalizationContext: ['groups' => ['author:read']],
)]
class Author
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
#[Groups(['author:read', 'book:read'])]
private ?int = null;
#[ORM\Column(length: 255)]
#[Groups(['author:read', 'book:read'])]
private ?string = null;
#[ORM\Column(type: 'text', nullable: true)]
#[Groups(['author:read'])]
private ?string = null;
#[ORM\OneToMany(mappedBy: 'author', targetEntity: Book::class)]
#[Groups(['author:read'])]
private Collection ;
public function __construct()
{
->books = new ArrayCollection();
}
// Getters and setters...
}<?php
// src/Entity/Book.php (with relation)
namespace App\Entity;
use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Metadata\Get;
use ApiPlatform\Metadata\GetCollection;
use ApiPlatform\Metadata\Link;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Serializer\Annotation\Groups;
#[ORM\Entity]
#[ApiResource(
normalizationContext: ['groups' => ['book:read']],
)]
// Subresource: GET /api/authors/{authorId}/books
#[ApiResource(
uriTemplate: '/authors/{authorId}/books',
operations: [new GetCollection()],
uriVariables: [
'authorId' => new Link(
fromProperty: 'books',
fromClass: Author::class
),
],
normalizationContext: ['groups' => ['book:read']],
)]
class Book
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
#[Groups(['book:read', 'author:read'])]
private ?int = null;
#[ORM\Column(length: 255)]
#[Groups(['book:read', 'author:read'])]
private ?string = null;
#[ORM\ManyToOne(targetEntity: Author::class, inversedBy: 'books')]
#[ORM\JoinColumn(nullable: false)]
#[Groups(['book:read'])]
private ?Author = null;
// Getters and setters...
}Sicherheit und Zugriffskontrolle
API Platform integriert sich nahtlos mit Symfonys Sicherheitssystem. Voters und Sicherheitsausdruecke kontrollieren den Ressourcenzugriff. Fuer eine vollstaendige Uebersicht der Symfony-Sicherheitsmuster siehe Symfony Security: Voters, Firewalls und Interview-Fragen.
<?php
// src/Entity/Order.php
namespace App\Entity;
use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Metadata\Get;
use ApiPlatform\Metadata\GetCollection;
use ApiPlatform\Metadata\Post;
use ApiPlatform\Metadata\Patch;
use ApiPlatform\Metadata\Delete;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity]
#[ApiResource(
operations: [
// List: authenticated users see their orders
new GetCollection(
security: "is_granted('ROLE_USER')",
// Automatic filter by connected user
provider: UserOrdersProvider::class,
),
// Creation: any authenticated user
new Post(
security: "is_granted('ROLE_USER')",
processor: CreateOrderProcessor::class,
),
// Read: owner or admin
new Get(
security: "is_granted('ROLE_ADMIN') or object.getCustomer() == user",
securityMessage: "Access denied to this order.",
),
// Modification: admin only
new Patch(
security: "is_granted('ROLE_ADMIN')",
),
// Deletion: admin only
new Delete(
security: "is_granted('ROLE_ADMIN')",
),
],
)]
class Order
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int = null;
#[ORM\ManyToOne(targetEntity: User::class)]
#[ORM\JoinColumn(nullable: false)]
private ?User = null;
#[ORM\Column(length: 50)]
private ?string = 'pending';
#[ORM\Column(type: 'decimal', precision: 10, scale: 2)]
private ?string = null;
#[ORM\Column]
private ?\DateTimeImmutable = null;
// Getters...
public function getCustomer(): ?User
{
return ->customer;
}
}Der Ausdruck object.getCustomer() == user bietet Zugriff auf die aktuelle Entitaet und den angemeldeten Benutzer fuer feinkoernige Pruefungen.
Automatisierte API-Tests
API Platform stellt PHPUnit-Traits fuer einfaches Testen von Endpunkten bereit.
<?php
// tests/Api/BookTest.php
namespace App\Tests\Api;
use ApiPlatform\Symfony\Bundle\Test\ApiTestCase;
use App\Entity\Book;
use App\Factory\BookFactory;
use App\Factory\UserFactory;
use Zenstruck\Foundry\Test\Factories;
use Zenstruck\Foundry\Test\ResetDatabase;
class BookTest extends ApiTestCase
{
use ResetDatabase;
use Factories;
public function testGetCollection(): void
{
// Create test data
BookFactory::createMany(30);
// GET request on collection
= static::createClient()->request('GET', '/api/books');
// Assertions
->assertResponseIsSuccessful();
->assertResponseHeaderSame('content-type', 'application/ld+json; charset=utf-8');
->assertJsonContains([
'@context' => '/api/contexts/Book',
'@type' => 'Collection',
'totalItems' => 30,
]);
// Verify pagination (20 items per page)
->assertCount(20, ->toArray()['member']);
}
public function testCreateBook(): void
{
= UserFactory::createOne(['roles' => ['ROLE_ADMIN']]);
static::createClient()->request('POST', '/api/books', [
'auth_bearer' => ->getToken(),
'json' => [
'title' => 'Clean Code',
'description' => 'A Handbook of Agile Software Craftsmanship',
'isbn' => '9780132350884',
],
]);
->assertResponseStatusCodeSame(201);
->assertJsonContains([
'@type' => 'Book',
'title' => 'Clean Code',
]);
}
public function testCreateBookValidationFails(): void
{
= UserFactory::createOne(['roles' => ['ROLE_ADMIN']]);
static::createClient()->request('POST', '/api/books', [
'auth_bearer' => ->getToken(),
'json' => [
'title' => '', // Empty title = error
'isbn' => 'invalid-isbn',
],
]);
->assertResponseStatusCodeSame(422);
->assertJsonContains([
'@type' => 'ConstraintViolationList',
'violations' => [
['propertyPath' => 'title', 'message' => 'Title is required'],
],
]);
}
private function getToken(object ): string
{
// Implementation depends on your authentication system
return 'test_token';
}
}Sources
- API Platform 4.4 Release Notes - Komponierbare Filter, deprecated #[ApiFilter], OpenAPI 3.2
- API Platform Dokumentation - Offizielle Installations- und Konfigurationsanleitungen
- Symfony Serializer Komponente - Serialisierungsgruppen und Normalisierung
API Platform Symfony Best Practices Checkliste
API Platform mit Symfony repraesentiert den Stand der Technik fuer die Erstellung professioneller REST-APIs in PHP. Die klare Trennung zwischen State Providers (Lesen) und State Processors (Schreiben), kombiniert mit Serialisierungsgruppen und dem Validierungssystem, ermoeglicht den Aufbau robuster und wartbarer APIs.
Checkliste fuer Qualitaets-APIs
- Unterschiedliche Serialisierungsgruppen fuer Lesen und Schreiben verwenden
- State Processors fuer Geschaeftslogik implementieren (Passwort-Hashing, Benachrichtigungen)
- Filter fuer Suche und Sortierung konfigurieren (von deprecated #[ApiFilter] zu komponierbaren Filtern migrieren)
- Validierungen pro Operation mit Gruppen anwenden
- Endpunkte mit Sicherheitsausdruecken schuetzen
- Funktionale Tests fuer jeden Endpunkt schreiben
- API ueber OpenAPI-Metadaten dokumentieren
Fang an zu üben!
Teste dein Wissen mit unseren Interview-Simulatoren und technischen Tests.
API Platforms Philosophie foerdert Komposition ueber Vererbung und Konfiguration ueber Konvention. Das Ergebnis: skalierbare, testbare APIs, die den REST/JSON-LD-Standards entsprechen und vom ersten Tag an produktionsbereit sind.
Findest du den Bug in Symfony?
Ein echter Codeausschnitt, ein versteckter Bug, ein Versuch pro Tag. Zum Ausprobieren ohne Konto.

Geschrieben von
Anthony Fillion-MailletGründer von SharpSkill
Seit über 10 Jahren Fullstack-Entwickler. Er leitet SharpSkill und verantwortet alles, was hier erscheint.
Aktualisiert am 12. Oktober 2026
Tags
Teilen
Verwandte Artikel

API Platform Symfony REST: Vollständiges Tutorial und Interview-Fragen 2026
REST APIs mit API Platform 4.3 und Symfony 7 entwickeln. State Providers, Processors, Serialisierungsgruppen und typische Interview-Fragen für Symfony-Entwickler.

Doctrine ORM: Beziehungen in Symfony meistern
Vollständiger Leitfaden zu Doctrine-ORM-Beziehungen in Symfony. OneToMany, ManyToMany, Ladestrategien und Performance-Optimierung mit praktischen Beispielen.

Symfony-Interviewfragen: Top 25 in 2026
Die 25 häufigsten Symfony-Interviewfragen. Architektur, Doctrine ORM, Services, Security, Formulare und Tests mit ausführlichen Antworten und Codebeispielen.