0
0
Rest APIprogramming~5 mins

Resource-based design thinking in Rest API - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Resource-based design thinking
O(n)
Understanding Time 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.

Scenario Under Consideration

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.

Identify Repeating Operations

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.
How Execution Grows With Input

As the number of resources grows, the server does more work formatting each one.

Input Size (n)Approx. Operations
1010 formatting operations
100100 formatting operations
10001000 formatting operations

Pattern observation: The work grows directly with the number of resources.

Final Time Complexity

Time Complexity: O(n)

This means the time to handle the request grows in a straight line as the number of resources increases.

Common Mistake

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

Interview Connect

Understanding how your API's work grows with data size shows you can design efficient and scalable services, a key skill in real projects.

Self-Check

"What if we added pagination to this API? How would the time complexity change?"