API & JSON
Sometimes the "view" is JSON for your React/Vue app. Symfony can stay thin (
JsonResponse) or grow into API Platform. Start thin.
Quick JSON from a controller
php
<?php
#[Route('/api/posts', name: 'api_posts_index', methods: ['GET'])]
public function apiIndex(PostRepository $posts): JsonResponse
{
$data = array_map(static fn (Post $p) => [
'id' => $p->getId(),
'title' => $p->getTitle(),
], $posts->findBy([], ['id' => 'DESC'], 20));
return $this->json($data);
}Comments for the code above:
$this->json()uses the Serializer under the hood when you pass objects with groups - arrays stay simple- Set
methods: ['GET']explicitly for API clarity - Don't leak entities with circular associations - map DTOs / arrays until you learn serialization groups
Accepting JSON bodies
php
<?php
$data = json_decode($request->getContent(), true, 512, JSON_THROW_ON_ERROR);
// validate $data (Validator component or a DTO + constraints)Or deserialize into an object with the Serializer. For learning, json_decode + explicit validation is honest and readable.
CSRF note for SPAs
Cookie session auth + SPA often needs CSRF strategy or token auth (JWT / opaque API tokens). Don't copy HTML form CSRF blindly into a JSON API - read Security docs for your chosen authenticator.
API Platform (pointer)
API Platform sits on Symfony and gives you OpenAPI, CRUD resources, filters - huge for API-heavy products. It's intentionally out of scope here; once controllers + Doctrine feel boring, try their tutorial.
FE mental map
| Your SPA | Symfony side |
|---|---|
fetch('/api/posts') | JsonResponse controller |
| React Query keys | cache headers / ETag later |
| Zod parse on client | Validator on server (always) |
Next: bin/console day-to-day.
Best,
-- ł.