Symfony 7: API Platform va Cac Thuc Hanh Tot Nhat

Huong dan day du xay dung REST API chuyen nghiep voi Symfony 7 va API Platform 4. State Providers, Processors, validation, va serialization duoc giai thich voi vi du thuc te.

Huong dan API Platform voi Symfony 7 — Cac Thuc Hanh Tot Nhat 2026

API Platform 4 thay doi cach tao REST API va GraphQL voi Symfony. Phien ban 4.4, phat hanh vao thang 9 nam 2026, mang den composable filters, deprecated #[ApiFilter] decorators, va ho tro native OpenAPI 3.2. Ket hop voi service container va autowiring cua Symfony, viec xay dung API chuyen nghiep tro nen don gian.

Co gi moi trong API Platform 4.4

Phien ban 4.4 deprecated legacy #[ApiFilter] decorators (du kien go bo o 6.0) va thay the bang composable filters nhu ComparisonFilter, OrFilter, va ChainFilter. Scalar UI thay the Swagger UI mac dinh tu 4.3, va OpenAPI 3.2 duoc ho tro day du. Xem release notes chinh thuc de biet huong dan di chuyen.

Cai Dat va Cau Hinh Ban Dau

API Platform duoc cai dat chi voi vai lenh thong qua Symfony Flex. Cau hinh mac dinh da du cho hau het cac truong hop su dung va van co the tuy chinh hoan toan.

bash
# 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 api

Symfony Flex tu dong cau hinh routes, tai lieu OpenAPI, va giao dien Scalar UI co the truy cap tai /api. Tai lieu API Platform bao gom tat ca cac tuy chon cau hinh.

yaml
# 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: 100

Cau hinh nay xac dinh cac dinh dang serialization, phan trang toan cuc, va metadata tai lieu API.

Tao API Resource Don Gian

Thuoc tinh #[ApiResource] expose mot Doctrine entity nhu REST resource. API Platform tu dong tao cac endpoint CRUD, tai lieu OpenAPI, va validation co ban.

php
<?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 \;
    }
}

Entity nay tao ra sau endpoint: GET /api/books, POST /api/books, GET /api/books/{id}, PUT /api/books/{id}, PATCH /api/books/{id}, va DELETE /api/books/{id}.

Khuyen nghi UUID v7

API Platform ho tro native UUID v7 lam identifier. Cach tiep can nay cai thien bao mat (identifier khong the doan truoc) va hieu suat (sap xep tu nhien theo ngay tao).

Serialization Groups de Kiem Soat Du Lieu Expose

Serialization groups xac dinh chinh xac thuoc tinh nao duoc expose khi doc (normalization) va ghi (denormalization). Su tach biet nay rat quan trong cho bao mat va tinh linh hoat cua API. Doi voi cac tinh huong serialization phuc tap, thanh phan Symfony Serializer cung cap cac tuy chon tuy chinh bo sung.

php
<?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;
    }
}

Voi cau hinh nay, plainPassword khong bao gio duoc expose trong response nhung co the gui khi tao hoac cap nhat.

Sẵn sàng chinh phục phỏng vấn Symfony?

Luyện tập với mô phỏng tương tác, flashcards và bài kiểm tra kỹ thuật.

State Processors cho Logic Nghiep Vu

State Processors chan cac thao tac persistence de them logic nghiep vu. API Platform don gian hoa viec tao chung thong qua dependency injection dua tren attribute.

php
<?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(\, \, \, \);
    }
}

Pattern composition nay cho phep them bat ky logic nao (gui email, events, logging) trong khi van giu hanh vi persistence chuan. Doi voi kien truc event-driven, processors hoat dong tot voi Symfony Messenger.

Processor voi Logic Co Dieu Kien

Mot processor co the dieu chinh hanh vi dua tren loai operation.

php
<?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 cho Nguon Du Lieu Tuy Chinh

State Providers lay du lieu tu bat ky nguon nao: API ben ngoai, cache, files, hoac logic nghiep vu phuc tap.

php
<?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);
        });
    }
}

Provider nay duoc su dung tren operation rieng.

php
<?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
{
    // ...
}

Validation Nang Cao voi Dynamic Groups

API Platform tich hop native voi thanh phan Validator cua Symfony. Validation groups co the thay doi dua tren operation hoac context.

php
<?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...
}

Validation Dong voi Service

Doi voi cac quy tac validation phuc tap, group generator tuy chinh cung cap su linh hoat toan dien.

php
<?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 \;
    }
}
Hieu Suat Validation

Validation phuc tap co the anh huong den hieu suat. Doi voi import hang loat, can nhac tam thoi vo hieu hoa mot so validation hoac su dung async constraints.

Filters cho Query Linh Hoat

API Platform 4.4 thiet ke lai he thong filter voi composable filters. Legacy #[ApiFilter] decorator da deprecated (du kien go bo o 6.0), va co codemod de di chuyen.

php
<?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...
}

Cac filter nay tu dong tao tai lieu OpenAPI va cho phep query nhu:

text
GET /api/products?name=phone&price[gte]=100&price[lte]=500&isActive=true&sort[price]=asc

API Platform 4.4 gioi thieu cac filter moi: StartSearchFilter, EndSearchFilter, WordStartSearchFilter, va composable wrappers nhu ComparisonFilter, OrFilter, va ChainFilter.

Quan He va Subresources

API Platform xu ly quan he entity mot cach de dang voi cac tuy chon serialization va subresources.

php
<?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
<?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...
}

Bao Mat va Kiem Soat Truy Cap

API Platform tich hop lien mach voi he thong bao mat cua Symfony. Voters va bieu thuc bao mat kiem soat truy cap resource. De co cai nhin tong quan ve cac pattern bao mat Symfony, xem Symfony Security: Voters, Firewalls va Cau Hoi Phong Van.

php
<?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;
    }
}

Bieu thuc object.getCustomer() == user cung cap quyen truy cap vao entity hien tai va nguoi dung da ket noi de kiem tra chi tiet.

Kiem Thu API Tu Dong

API Platform cung cap PHPUnit traits de kiem thu endpoints de dang.

php
<?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';
    }
}

Nguon Tham Khao

Checklist Thuc Hanh Tot Nhat API Platform Symfony

API Platform voi Symfony dai dien cho tieu chuan hien dai nhat trong viec tao REST API chuyen nghiep bang PHP. Su tach biet ro rang giua State Providers (doc) va State Processors (ghi), ket hop voi serialization groups va he thong validation, cho phep xay dung API vung chac va de bao tri.

Checklist cho API Chat Luong

  • Su dung serialization groups khac nhau cho doc va ghi
  • Implement State Processors cho logic nghiep vu (hash mat khau, thong bao)
  • Cau hinh filters cho tim kiem va sap xep (di chuyen tu deprecated #[ApiFilter] sang composable filters)
  • Ap dung validation theo tung operation voi groups
  • Bao ve endpoints bang bieu thuc security
  • Viet functional tests cho moi endpoint
  • Tai lieu API thong qua metadata OpenAPI

Bắt đầu luyện tập!

Kiểm tra kiến thức với mô phỏng phỏng vấn và bài kiểm tra kỹ thuật.

Triet ly cua API Platform khuyen khich composition hon la inheritance, va configuration hon la convention. Ket qua la API co kha nang mo rong, de kiem thu, va tuan thu chuan REST/JSON-LD, san sang cho production tu ngay dau tien.

Thử thách hôm nay

Bạn có tìm ra lỗi trong Symfony không?

Một đoạn mã thật, một lỗi ẩn, mỗi ngày một lượt. Không cần tài khoản để thử.

Anthony Fillion-Maillet

Viết bởi

Anthony Fillion-Maillet

Người sáng lập SharpSkill

Lập trình viên fullstack hơn 10 năm. Anh điều hành SharpSkill và chịu trách nhiệm về mọi nội dung đăng tại đây.

Cập nhật ngày 12 tháng 10, 2026

Thẻ

#symfony
#api platform
#php
#rest api
#api development

Chia sẻ

Bài viết liên quan