JSON and API Representation Design
Design predictable JSON representations and understand serialization, nullability, naming, and compatibility.
JSON Fundamentals for APIs
JSON supports objects, arrays, strings, numbers, booleans, and null. API contracts should define which fields are required, optional, nullable, writable, and read-only.
Do not blindly serialize database documents. Database schemas and public API representations serve different purposes. An API may rename fields, omit internal fields, calculate values, combine data from multiple sources, or expose stable identifiers.
For example, an internal document may contain password hashes, audit metadata, internal flags, and database-specific identifiers. None of these should automatically become public API fields.
{
"id": "usr_42",
"name": "Suriya",
"email": "suriya@example.com",
"createdAt": "2026-10-12T10:00:00Z"
}Designing Consistent Response Shapes
An API becomes easier to consume when similar endpoints use similar structures.
A collection might return an object containing data, pagination metadata, and links. A single resource can return the resource directly or consistently inside data, depending on the API convention.
Avoid unpredictable behavior such as returning an array from one collection endpoint and an object with items from another without a strong reason.
Consistency should also apply to dates, identifiers, naming conventions, errors, pagination, and null handling.
ISO 8601 stringsStable identifiersDocument semanticsSerialization and Backward Compatibility
Serialization converts internal application data into a transferable representation. Deserialization performs the reverse operation.
API evolution requires careful consideration of existing clients. Adding an optional response field is often backward compatible. Removing a field, changing its type, changing meaning, or making an optional request field mandatory can break consumers.
Prefer additive changes where possible. Treat public API schemas as contracts that may have clients you cannot directly observe.
- API representations should be designed independently of database schemas.
- Consistent response shapes reduce client complexity.
- Backward compatibility is a primary API design concern.