Nested resources in Rest API - Time & Space Complexity
When working with nested resources in REST APIs, it's important to understand how the number of operations grows as we access deeper or more items.
We want to know how the time to get data changes when we have nested lists or details.
Analyze the time complexity of the following code snippet.
GET /users/{userId}/posts
// This endpoint fetches all posts for a specific user.
// It first finds the user, then retrieves their posts list.
This code fetches posts nested under a user resource.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Retrieving each post in the user's posts list.
- How many times: Once for each post belonging to the user.
As the number of posts for a user grows, the time to fetch all posts grows proportionally.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 posts | 10 operations to retrieve posts |
| 100 posts | 100 operations to retrieve posts |
| 1000 posts | 1000 operations to retrieve posts |
Pattern observation: The operations increase directly with the number of posts.
Time Complexity: O(n)
This means the time to get all posts grows in a straight line as the number of posts grows.
[X] Wrong: "Fetching nested resources is always constant time because it's just one API call."
[OK] Correct: Even though it's one call, the server processes each nested item, so time grows with the number of nested items.
Understanding how nested resource calls scale helps you design APIs and explain performance clearly in real projects.
"What if the API also fetched comments for each post nested inside? How would the time complexity change?"