Why HTTP methods define intent in Rest API - Performance Analysis
When working with HTTP methods, it's important to understand how the server handles each request type.
We want to see how the server's work grows as requests increase, based on the method's intent.
Analyze the time complexity of handling different HTTP methods in a REST API.
@app.route('/items', methods=['GET', 'POST', 'PUT', 'DELETE'])
def items():
if request.method == 'GET':
return get_all_items()
elif request.method == 'POST':
return create_item(request.data)
elif request.method == 'PUT':
return update_item(request.data)
elif request.method == 'DELETE':
return delete_item(request.data)
This code handles different HTTP methods to get, create, update, or delete items.
Look at what repeats when the server processes requests.
- Primary operation: Iterating over items for GET or searching for the item to update/delete.
- How many times: Depends on the number of items stored (n).
As the number of items grows, the server work changes depending on the method.
| Input Size (n) | Approx. Operations for GET |
|---|---|
| 10 | 10 operations (checking each item) |
| 100 | 100 operations |
| 1000 | 1000 operations |
For GET, work grows linearly with the number of items. For POST, work is usually constant since it adds one item. PUT and DELETE may also grow linearly if searching is needed.
Time Complexity: O(n)
This means the server's work grows in direct proportion to the number of items when handling GET, PUT, or DELETE requests.
[X] Wrong: "All HTTP methods take the same time regardless of data size."
[OK] Correct: Some methods like GET or DELETE may need to look through many items, so their time grows with data size.
Understanding how HTTP methods affect server work helps you explain API design choices clearly and confidently.
"What if the server used an index to find items for PUT and DELETE? How would that change the time complexity?"