#[MapRequestPayload] in Symfony: a DTO for the JSON body

The #[MapRequestPayload] attribute fills a DTO with the request's JSON body and validates it: the Symfony controller only receives correct data.

final class ReservationDemande
{
    #[Assert\NotBlank(message: 'Enter your name.')]
    public ?string $nom = null;

    #[Assert\NotNull(message: 'Enter the number of guests.')]
    #[Assert\Range(min: 1, max: 12)]
    public ?int $personnes = null;
}

#[Route('/api/reservations', methods: ['POST'])]
public function reserver(#[MapRequestPayload] ReservationDemande $demande): JsonResponse
{
    // Here, the request has been read and validated; otherwise, Symfony has already answered 400 or 422.
}

Without it, an API controller decodes the JSON, checks every field, converts the types and builds its error responses. With the attribute on a typed argument, Symfony deserializes, validates, and answers in the controller's place: 400 for unreadable JSON, 422 with the list of violations when a rule isn't met. The classic trap is mapping an entity directly: the client can then send fields it shouldn't touch. A DTO only contains what the client is allowed to send, and its validation doesn't depend on the database.

The exercises have you receive bookings sent by magic pigeon, with their DTO and their error messages, then build the API that lets the guilds register their members for the tavern's evenings, with the right HTTP codes for each refusal.

2 exercises work on this concept, by writing code in the browser.

In the tracks

Related concepts

DTOJSON APIHTTP status codesStateless firewall