JSON API Design
JSON (JavaScript Object Notation) is the most common format for REST API responses. Let's learn how to design clean, consistent JSON structures.
JSON Basics
JSON supports these data types:
- Objects:
{ "key": "value" } - Arrays:
[1, 2, 3] - Strings:
"hello" - Numbers:
42,3.14 - Booleans:
true,false - Null:
null
Naming Conventions
Use camelCase for Properties
{
"firstName": "Alice",
"lastName": "Smith",
"emailAddress": "alice@example.com",
"createdAt": "2024-01-15T10:30:00Z"
}
Some APIs use snake_case (first_name). Either is fine, but be consistent.
Use Meaningful Names
// Bad
{ "n": "Alice", "e": "alice@example.com" }
// Good
{ "name": "Alice", "email": "alice@example.com" }
Use Plural for Arrays
{
"users": [...], // Good - plural for array
"orderItems": [...] // Good - plural for array
}
Single Resource Response
A single resource should be a flat object with an ID:
{
"id": "user_123",
"name": "Alice Smith",
"email": "alice@example.com",
"role": "admin",
"createdAt": "2024-01-15T10:30:00Z",
"updatedAt": "2024-01-16T14:20:00Z"
}
Collection Response
For collections, use a wrapper with metadata:
{
"data": [
{ "id": "1", "name": "Alice" },
{ "id": "2", "name": "Bob" }
],
"meta": {
"total": 100,
"page": 1,
"perPage": 20
}
}
Handling Related Resources
Option 1: Nested Objects (for small relations)
{
"id": "order_123",
"total": 99.99,
"customer": {
"id": "user_456",
"name": "Alice Smith",
"email": "alice@example.com"
}
}
Option 2: IDs Only (for references)
{
"id": "order_123",
"total": 99.99,
"customerId": "user_456"
}
Option 3: Links (HATEOAS)
{
"id": "order_123",
"total": 99.99,
"links": {
"self": "/orders/123",
"customer": "/users/456"
}
}
Date and Time
Always use ISO 8601 format with timezone:
{
"createdAt": "2024-01-15T10:30:00Z",
"scheduledFor": "2024-01-20T14:00:00-05:00"
}
Handling Null vs Absent
Be consistent about when to include null values:
// Option 1: Include null
{ "name": "Alice", "nickname": null }
// Option 2: Omit null fields
{ "name": "Alice" }
Document your approach in API guidelines.
Exercise: Design JSON Responses
Loading JavaScript Exercise...
Response Envelopes
Some APIs wrap all responses in an envelope:
{
"status": "success",
"data": {
"id": "123",
"name": "Alice"
}
}
This is optional - HTTP status codes already indicate success/failure.
Best Practices Summary
| Practice | Example |
|---|---|
| Use camelCase | firstName, not first_name |
| Use ISO 8601 dates | 2024-01-15T10:30:00Z |
| Wrap collections | { "data": [...], "meta": {...} } |
| Include resource IDs | Always include id field |
| Be consistent | Same structure everywhere |
| Document nulls | Define null vs absent policy |

