Implementing Resource Expansion
1. Using Expand Query Parameter
| Param | Example |
|---|---|
expand | ?expand=author,comments |
include (JSON:API) | ?include=author,comments.user |
embed | ?embed=author |
2. Implementing Nested Resource Embedding
Example: Embedded Author
{
"id": 100,
"title": "REST Best Practices",
"authorId": 42,
"_embedded": {
"author": {"id": 42, "name": "Alice", "email": "alice@example.com"}
}
}
3. Using Include Parameter
JSON:API standard for sideloading related resources.
| Format | Result |
|---|---|
?include=author | Single relation |
?include=author,comments | Multiple relations |
?include=comments.user | Nested relation |
4. Handling Circular References
Warning: User → posts → user → posts → ... can loop forever. Use ID references after first depth or limit depth.
| Strategy | Implementation |
|---|---|
| Depth limit | Hard cap (e.g. 3 levels) |
| ID-only after depth | Return reference, not full object |
JSON:API included | Flat list of unique resources |
5. Limiting Expansion Depth
| Depth | Recommendation |
|---|---|
| 1 | Direct relations only (safe default) |
| 2 | Common: ?expand=author.profile |
| 3+ | Reject or use GraphQL |
6. Implementing Selective Expansion
7. Optimizing Database Queries
| Anti-Pattern | Solution |
|---|---|
| N+1 queries on expansion | Eager load via JOIN or IN query |
| Loading all relations | Load only requested via reflection |
| Deep nested loads | Use DataLoader pattern (batch + cache) |
8. Combining Expansion with Field Selection
| Combination | Effect |
|---|---|
expand=X&fields=X.a,X.b | Embed X with only fields a, b |
| JSON:API style | include=author&fields[users]=name |
9. Documenting Expandable Resources
| Doc Element | Content |
|---|---|
| Expandable list | Names of relations |
| Default expansion | None or specific relations |
| Performance impact | Note expensive expansions |
10. Handling Missing Related Resources
| Scenario | Response |
|---|---|
| Relation is null | Embed null or omit field |
| Relation deleted | Return ID + tombstone or omit |
| Permission denied on relation | Embed minimal/redacted version |