JSON API with Symfony: answering in JSON with the right HTTP codes

A JSON API with Symfony: routes that answer in JSON rather than HTML, with a precise HTTP code for each outcome, success and refusal alike.

#[Route(format: 'json')]
class SoireeController extends AbstractController
{
    #[Route('/api/soirees', name: 'api_soirees', methods: ['GET'])]
    public function soirees(SoireeRepository $soirees, ClockInterface $horloge): JsonResponse
    {
        return $this->json(array_map($this->resume(...), $soirees->findAVenir($horloge->now())));
    }
}
// Business refusal: $this->json(['erreur' => '…'], JsonResponse::HTTP_CONFLICT);

An API client doesn't read a page: it reads a status and a body. $this->json() passes the data to the Serializer and sets the Content-Type header; its second argument carries the code (201 on creation, 409 when the resource's state prevents the action, 422 for invalid data). format: 'json' on the route also makes errors thrown in the action come out as JSON, the 404 for an unknown evening included. The trap: passing an entity as is to $this->json(). The Serializer reads all its getters and follows its relations: it goes round in circles, or publishes what should have stayed private, down to an employee's e-mail and password hash.

The exercises have you publish the tavern's menu as JSON, from the cheapest dish to the most expensive, then build the storytelling evenings API for the guilds: the list open to everyone, and registration with its 201, 401, 404, 409 and 422 responses.

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

In the tracks

Related concepts

Serializer#[Groups]#[MapRequestPayload]HTTP status codesStateless firewall