JSON APIs — Predictable Responses
The mobile team writes code against your API once and expects it to keep working. If /books/42 sometimes returns a list, sometimes an object, and signals errors with a 200 and a random message, every client ends up full of special cases. A predictable JSON shape is a promise that lets other people build on you.
The rule
Same shape every time; the status says whether it worked.
JSON is the text format nearly every web API uses. It has just six kinds of value:
- object:
{"title": "The Salt Road", "price": 399} - array:
[1, 2, 3] - string:
"text", always in double quotes - number:
399or4.5 - boolean:
trueorfalse - null:
null
Keys must be double-quoted strings. There are no comments, no trailing commas and no date type (dates are usually strings like "2026-09-25").
A predictable API picks shapes and never varies them:
{
"id": 42,
"title": "The Salt Road",
"price": 399,
"author": {"id": 7, "name": "Meera Iyer"},
"published_on": "2019-03-14"
}Lists come wrapped with paging information, so fields can be added later without breaking clients:
{
"items": [{"id": 42, "title": "The Salt Road"}],
"page": 1,
"total": 5000
}Errors get an honest status code and one consistent body shape:
{
"error": {
"code": "book_not_found",
"message": "No book with id 9999"
}
}The code is stable text that programs can check; the message is for humans and may change.
Consistency also covers the small choices. Pick one naming style for keys, such as snake_case, and use it everywhere. Pick one format for dates. Send money as whole numbers in the smallest unit (rupees here, or paise), because decimal fractions invite rounding surprises.
The shortcut
Before shipping an endpoint, check status, shape, sameness: does the status code tell the truth, is the body a documented shape, and does it match the shape of every similar endpoint?
A missing book
GET /books/9999→ status404, body{"error": {"code": "book_not_found", ...}}.
The trap is the "always 200" API: 200 OK with {"success": false}. Clients, caches and dashboards all believe the request worked, and every client has to dig through the body to find out otherwise.
Drills
Answer fast — trust the rule.
Which of these is valid JSON?
A client asks for a book that does not exist. What is the best response?
Why wrap a list as {"items": [...], "page": 1, "total": 5000} instead of returning a bare array?
In an error body, why include a code like invalid_quantity as well as a message?
Remember
- Same shape every time; the status says whether it worked.
- Check status, shape, sameness before shipping an endpoint.
- JSON: double quotes, no trailing commas, no comments; dates travel as strings.
