Skip to content

Lesson 8 of 9 · 24m

APIs, Serialization, and HTTP Caching Without Regret

Controllers as APIs, serializer groups, validation errors, versioning, ETags, cache headers, and integration design that does not repaint itself yearly.

Most enterprise PHP systems spend more time integrating than rendering pages. Symfony is strong here because HTTP is its native language. The failure mode is treating JSON as an afterthought and exposing whichever object happened to be nearby.

Do not serialize the persistence model by accident

Entities contain relations, lazy proxies, internal ids, sensitive fields, and circular references. Expose an output contract:

final readonly class InvoiceOutput
{
    public function __construct(
        public string $id,
        public int $totalCents,
        public string $currency,
        public string $status,
    ) {}
}

Yes, this is more code. It is also the difference between an API and a database dump with indentation.

Errors are part of the contract

Validation failures should be stable and machine-readable:

{
  "title": "Validation failed",
  "status": 422,
  "violations": [
    {"property": "email", "message": "Invalid email address."}
  ]
}

You do not need RFC purity, but you do need consistency. Client teams can code around predictable errors; they cannot code around exceptions rendered differently in dev and prod.

HTTP caching is free performance — if truthful

$response = new JsonResponse($payload);
$response->setPublic();
$response->setMaxAge(60);
$response->setEtag(md5(json_encode($payload)));

ETags, Cache-Control, and invalidation are architecture. If personalized data becomes public cache, the performance win becomes a report to legal. Separate public, private, and never-cache resources deliberately.

Version behavior before clients force you to

Additive changes are usually safe: new optional fields or endpoints. Removing fields, changing types, changing meaning, or tightening validation is breaking. Contract tests catch accidental serializer changes:

$client->request('GET', '/api/invoices/'.$id);
self::assertResponseStatusCodeSame(200);
self::assertJsonContains(['status' => 'issued']);

Field notes

  • Return 201 for creation with a useful Location header; 200 for everything is laziness.
  • 204 means no body; do not attach a JSON document to it.
  • Make timestamps UTC and document them.
  • Provide idempotency keys or natural uniqueness where clients retry writes.
  • Build APIs around use cases, not table names. /customers/123/invoices is useful; /invoice-lines-batch-mutation usually means missing design.

Was this lesson helpful?

Sign in to rate