Implementing Resource Expansion

1. Using Expand Query Parameter

ParamExample
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.

FormatResult
?include=authorSingle relation
?include=author,commentsMultiple relations
?include=comments.userNested relation

4. Handling Circular References

Warning: User → posts → user → posts → ... can loop forever. Use ID references after first depth or limit depth.
StrategyImplementation
Depth limitHard cap (e.g. 3 levels)
ID-only after depthReturn reference, not full object
JSON:API includedFlat list of unique resources

5. Limiting Expansion Depth

DepthRecommendation
1Direct relations only (safe default)
2Common: ?expand=author.profile
3+Reject or use GraphQL

6. Implementing Selective Expansion

Example: Selective Expansion + Field Selection

GET /articles?expand=author&fields=title,author.name

7. Optimizing Database Queries

Anti-PatternSolution
N+1 queries on expansionEager load via JOIN or IN query
Loading all relationsLoad only requested via reflection
Deep nested loadsUse DataLoader pattern (batch + cache)

8. Combining Expansion with Field Selection

CombinationEffect
expand=X&fields=X.a,X.bEmbed X with only fields a, b
JSON:API styleinclude=author&fields[users]=name

9. Documenting Expandable Resources

Doc ElementContent
Expandable listNames of relations
Default expansionNone or specific relations
Performance impactNote expensive expansions
ScenarioResponse
Relation is nullEmbed null or omit field
Relation deletedReturn ID + tombstone or omit
Permission denied on relationEmbed minimal/redacted version