Resource-based design thinking in Rest API - Time & Space Complexity
When designing REST APIs using resource-based thinking, it's important to understand how the number of resources affects the work the server does.
We want to know how the time to handle requests grows as the number of resources increases.
Analyze the time complexity of the following REST API endpoint that lists all resources.
GET /api/resources
// Server code example:
function getAllResources() {
const resources = database.getAll();
return resources.map(resource => format(resource));
}
This code fetches all resources from the database and formats each one before sending the response.
Look for repeated actions in the code.
- Primary operation: Looping over all resources to format each one.
- How many times: Once for each resource in the database.
As the number of resources grows, the server does more work formatting each one.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 formatting operations |
| 100 | 100 formatting operations |
| 1000 | 1000 formatting operations |
Pattern observation: The work grows directly with the number of resources.
Time Complexity: O(n)
This means the time to handle the request grows in a straight line as the number of resources increases.
[X] Wrong: "Fetching all resources is always fast because databases are optimized."
[OK] Correct: Even if the database is fast, the server still processes each resource one by one, so more resources mean more work and longer time.
Understanding how your API's work grows with data size shows you can design efficient and scalable services, a key skill in real projects.
"What if we added pagination to this API? How would the time complexity change?"