Nested Resources and Sub-Resources
You'll learn when to nest resources in your API paths versus keeping them flat with query parameters.
The Core Tension
You've already learned about resource naming—but what happens when resources belong to other resources? Should you design /users/123/posts or /posts?userId=123? Both retrieve a user's posts, but they carry different semantic meanings and design tradeoffs.
When to Nest: Ownership and Context
Nest resources when the sub-resource cannot exist without or is tightly owned by the parent:
/users/123/posts— posts belong to a specific user/orders/456/items— order items only exist within an order context/projects/789/tasks— tasks are scoped to a project
Nesting signals strong relationship and contextual dependency. The parent ID is mandatory to even identify the child resource.
When to Flatten: Flexible Querying
Use flat routes with filters when:
- The resource has independent identity:
/posts?userId=123(posts exist independently) - You need multi-filter flexibility:
/posts?userId=123&status=published&category=tech - Multiple "parent" relationships exist:
/comments?postId=999vs/comments?userId=123
Flattening treats the parent as just another filter criterion, not a required context.
Practical Guidelines
Nest up to 2 levels maximum (/resource/id/sub-resource). Deeper nesting (/a/1/b/2/c/3) becomes unwieldy and hard to maintain. Beyond two levels, flatten with filters.
Key Takeaway: Nest resources when the parent-child relationship is mandatory and ownership-based (/users/123/posts); use flat routes with filters when resources are independently queryable or need flexible filtering (/posts?userId=123).