Lesson 2 of 9 · 21m
Serialization and Response Shapes
Separate internal models from public representations, serialize deliberately, and avoid leaking database structure through JSON.
The fastest way to paint yourself into a corner is to json_encode($entity) and call it an API. Your database rows are not your public contract. They contain internal IDs, soft-delete flags, timestamps you do not want to expose, and relationships that are expensive to serialize.
Build a representation layer
A serializer or resource object translates domain state into the exact JSON you promised. In Laravel, API resources do this; in Symfony, Serializer groups do the same job.
final class InvoiceResource
{
public function toArray(Invoice $invoice): array
{
return [
'id' => $invoice->publicId,
'number' => $invoice->number,
'status' => $invoice->status->value,
'total' => ['amount' => $invoice->totalCents, 'currency' => 'USD'],
'issuedAt' => $invoice->issuedAt?->format(DATE_ATOM),
'links' => ['self' => '/v1/invoices/' . $invoice->publicId],
];
}
}Notice what is absent: the numeric primary key, the tenant ID, internal notes, and every eager-loaded relationship. If a client needs line items, expose them deliberately as a nested representation or a linked endpoint.
Money, dates, and nulls need rules
Use integers for money (totalCents, not 10.99) and include a currency code. Emit dates in RFC 3339 / ISO-8601 with a timezone, usually UTC. Distinguish null from missing: a missing key means the server did not include the field; null means the field exists and is empty.
{
"id": "inv_9c8b7a",
"status": "open",
"total": {"amount": 129900, "currency": "USD"},
"issuedAt": "2026-11-29T14:05:00Z",
"dueAt": null
}Control JSON encoding behavior
PHP's JSON defaults are not always what you expect in an API context. Be explicit at the boundary:
json_encode($payload, JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);JSON_THROW_ON_ERROR prevents a serialization failure from becoming an empty 200 response. The other flags keep URLs and Unicode readable in logs and client debugging.
Beware accidental cardinality
A response shape that sometimes returns one object and sometimes an array is a bug factory. Pick one shape per field. If items is a collection, it is always an array, even when empty. Embedded relationships should also have hard limits — serializing 20,000 line items into one invoice response is an outage disguised as a feature.
Field notes
- Do not expose enums as database integers unless clients truly need them; string values are clearer and safer to evolve.
- Deprecate fields in documentation before removing them. A JSON consumer cannot warn at compile time.
- Avoid serialized PHP object payloads or framework-specific error traces. Clients should receive stable contracts, not implementation debris.
- Test serialization with missing optional relations. Lazy loading in a serializer can turn one request into hundreds of queries.
Was this lesson helpful?