Skip to content
Tutorials Center
My learning

Topics

Lesson 58 of 62 ยท Projects

Project: A Bookstore JSON API

Build a bookstore JSON API in Symfony with serializer groups, request payload validation, safe filtering, sorting and pagination, plus runnable stand-ins.

In this project you build the HTTP API of a small bookstore. Clients can list books with filters, sorting and pages, fetch one book, create and update books and receive errors they can parse. APIs are mostly a matter of discipline: the same shapes, the same status codes and no surprises. Symfony gives you the parts, and this lesson shows how to assemble them.

The real Symfony code (entity, controller, DTOs) is read-only, because Symfony cannot run in the browser here. Two plain-PHP stand-ins run on the site and reproduce the interesting logic: a serializer with groups read from PHP attributes, validation errors in the problem-details format, and a SQLite list endpoint with whitelisted sorting, filters and pagination. Background: Building JSON APIs, The Serializer Component, Mapping Request Data to Objects and Validation.

The contract

Decide the contract before you write code. This is the whole API:

Method Path Success Errors
GET /api/books 200 with data and meta 400 for bad query parameters
GET /api/books/{id} 200 404
POST /api/books 201 with Location 400 malformed JSON, 422 validation
PUT /api/books/{id} 200 404, 422
DELETE /api/books/{id} 204 404

The list accepts page, perPage (maximum 50), sort (title, price, -price, -id), author (contains) and maxPrice (in cents).

sequenceDiagram
    participant C as Client
    participant K as Symfony kernel
    participant A as BookController
    participant V as Validator
    participant R as BookRepository
    C->>K: POST /api/books (JSON)
    K->>A: map payload to BookInput
    A->>V: validate
    alt invalid
        V-->>C: 422 problem+json
    else valid
        A->>R: save
        R-->>C: 201 + Location + body
    end

Parsing, validation and persistence are separate steps; each can end the request with its own status code.

Entity and serializer groups

Never serialize an entity "as it is": a new column would instantly become public. Use serialization groups to decide which properties each response contains:

PHP
<?php
namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Serializer\Attribute\Groups;

#[ORM\Entity]
class Book
{
    #[ORM\Id, ORM\GeneratedValue, ORM\Column]
    #[Groups(['book:list', 'book:detail'])]
    private ?int $id = null;

    #[ORM\Column(length: 160)]
    #[Groups(['book:list', 'book:detail'])]
    private string $title = '';

    #[ORM\Column(length: 120)]
    #[Groups(['book:list', 'book:detail'])]
    private string $author = '';

    #[ORM\Column]
    #[Groups(['book:list', 'book:detail'])]
    private int $priceCents = 0;

    #[ORM\Column(length: 13, unique: true)]
    #[Groups(['book:detail'])]
    private string $isbn = '';

    #[ORM\Column(type: 'text', nullable: true)]
    #[Groups(['book:detail'])]
    private ?string $description = null;
}

Writes use a separate input class. It is the contract of the request body, so id can never be set by a client and validation rules live in one place:

PHP
<?php
namespace App\Dto;

use Symfony\Component\Validator\Constraints as Assert;

final class BookInput
{
    #[Assert\NotBlank, Assert\Length(max: 160)]
    public string $title = '';

    #[Assert\NotBlank, Assert\Length(max: 120)]
    public string $author = '';

    #[Assert\PositiveOrZero]
    public int $priceCents = 0;

    #[Assert\Isbn]
    public string $isbn = '';

    public ?string $description = null;
}

The controller

#[MapRequestPayload] deserializes the JSON body into BookInput and validates it; a malformed body becomes a 400 and failed constraints become a 422 automatically. #[MapQueryString] does the same for the query string with a filter DTO:

PHP
<?php
namespace App\Controller;

use App\Dto\BookFilter;
use App\Dto\BookInput;
use App\Entity\Book;
use App\Repository\BookRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Attribute\MapQueryString;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Attribute\MapRequestPayload;
use Symfony\Component\Routing\Attribute\Route;

#[Route('/api/books')]
final class BookController extends AbstractController
{
    #[Route('', methods: ['GET'])]
    public function list(BookRepository $books, #[MapQueryString] BookFilter $filter = new BookFilter()): JsonResponse
    {
        $page = $books->search($filter);

        return $this->json(
            ['data' => $page->items, 'meta' => ['page' => $page->number, 'pages' => $page->pages, 'total' => $page->total]],
            context: ['groups' => ['book:list']],
        );
    }

    #[Route('', methods: ['POST'])]
    public function create(#[MapRequestPayload] BookInput $input, BookRepository $books): JsonResponse
    {
        $book = $books->createFrom($input);

        return $this->json($book, 201, [
            'Location' => $this->generateUrl('book_show', ['id' => $book->getId()]),
        ], ['groups' => ['book:detail']]);
    }

    #[Route('/{id}', name: 'book_show', requirements: ['id' => '\d+'], methods: ['GET'])]
    public function show(Book $book): JsonResponse
    {
        return $this->json($book, context: ['groups' => ['book:detail']]);
    }
}

The default error format of MapRequestPayload is a JSON list of violations. Many APIs standardize on problem details (RFC 9457, media type application/problem+json), and the Serializer ships a normalizer for it. In the stand-in below you build that shape by hand so you can see what a client receives. It also implements a group-aware serializer that reads the #[Groups] attribute through Reflection, the same mechanism Symfony's AttributeLoader uses.

PHP Serializer groups and problem-details errors (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Notice that internalNote never appears: a property without a group is invisible. That is the allow-list behavior you want, because forgetting a group hides data rather than leaking it. Also note the 400 versus 422 split: a body that is not JSON cannot be understood at all (400), while a body that parses but breaks the rules is understood and rejected (422).

Filtering, sorting and pagination

The list endpoint is where APIs most often get sloppy. Three rules prevent most trouble:

  1. Whitelist sortable and filterable fields. Never paste ?sort= into SQL or DQL. Map each allowed name to a column yourself.
  2. Cap the page size. perPage=100000 is a denial-of-service request that looks polite.
  3. Return the paging data (total, pages) in the body or in Link headers so clients never construct URLs by hand.

In Symfony this logic lives in the filter DTO (#[Assert\Choice], #[Assert\Range]) and in BookRepository::search():

PHP
<?php
namespace App\Dto;

use Symfony\Component\Validator\Constraints as Assert;

final class BookFilter
{
    public function __construct(
        #[Assert\Positive] public int $page = 1,
        #[Assert\Range(min: 1, max: 50)] public int $perPage = 10,
        #[Assert\Choice(['title', '-title', 'price', '-price', 'id', '-id'])] public string $sort = 'title',
        #[Assert\Length(max: 120)] public ?string $author = null,
        #[Assert\PositiveOrZero] public ?int $maxPrice = null,
    ) {
    }
}

The stand-in implements the same endpoint over SQLite so you can try different query strings. The whitelist is a plain array that maps the public name to a column, and every value goes through a bound parameter.

PHP A paginated, filterable list endpoint on SQLite

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Check the interesting lines in the output. The author=% query matches nothing: the % was escaped, so it is searched as a literal character instead of acting as a wildcard. The injection attempt in sort never reaches SQL, it is rejected because it is not in the whitelist. And the second sort key, id ASC, keeps pages stable when two books have the same price.

Beyond the project

  • Resources and filters for free: API Platform Overview generates most of this (operations, filters, pagination, OpenAPI docs) from attributes on the entity. Building it by hand once, as here, makes it much easier to understand what API Platform does for you.
  • Authentication: protect /api with a token authenticator or access tokens and a stateless firewall (Login Forms and Authenticators).
  • Caching: add Cache-Control or ETag headers to GET responses (HTTP Caching).
  • Tests: use WebTestCase to post JSON and assert the status code and the problem-details body (Testing with PHPUnit).
  • Versioning: prefix the path (/api/v1) from day one; changing the shape of a response later is a breaking change.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why use serialization groups instead of serializing the entity directly?

    Groups act as an allow-list per response shape. Without them, every readable property, including internal ones, would become public.
  2. 2. A client sends a body that is not valid JSON. Which status fits best?

    400 means the server could not understand the request at all. 422 is for a body that parses but violates the rules.
  3. 3. Why does the stand-in map sort=price to a column through an array instead of using the value in SQL?

    Parameters bind values, not identifiers. The only safe way to let clients choose a column is to translate their choice through a fixed list.
  4. 4. What is the purpose of the second sort key, id ASC?

    Rows with the same title or price could come back in any order, which can duplicate or skip rows between pages. A unique tie-breaker fixes the order.
  5. 5. Which header should a successful POST that creates a book include?

    201 Created is accompanied by a Location header so the client knows where to fetch the new resource.

Summary

  • Write the contract first: paths, methods, status codes, error shape.
  • Use separate output shapes (serializer groups) and input classes (DTOs with validation); never expose or accept entities directly.
  • 400 for unreadable requests, 422 for valid syntax with broken rules, 404 for missing resources, 201 with Location for creation.
  • Whitelist sort and filter fields, cap page size, escape LIKE wildcards and use a unique tie-breaker.
  • Return paging metadata so clients never guess.

Finally, move slow work out of the request in Project: Async Report Generator.