HTTP Methods
HTTP methods (also called verbs) indicate the desired action to be performed on a given resource. The core methods are: * **GET**: Retrieve resource representat...
Definition
HTTP methods (also called verbs) indicate the desired action to be performed on a given resource. The core methods are:
- GET: Retrieve resource representation.
- POST: Create a new resource or execute a complex operation (like model inference).
- PUT: Replace/overwrite an existing resource.
- PATCH: Modify parts of an existing resource.
- DELETE: Remove a resource.
Why It Exists
Standardizing actions helps servers process requests correctly. For example, GET calls are designed to be safe and idempotent (making the call multiple times has no side effects and modifies nothing), allowing intermediate CDNs and web proxies to cache responses, saving network costs.
How It Works
METHOD CLASSIFICATIONS
┌─────────┬──────────────┬──────────────┬─────────────────────────────┐
│ Method │ Idempotent? │ Safe? │ Production Use Case │
├─────────┼──────────────┼──────────────┼─────────────────────────────┤
│ GET │ Yes │ Yes │ Fetch chat logs / status │
│ POST │ No │ No │ Generate LLM text completion│
│ PUT │ Yes │ No │ Update full profile config │
│ PATCH │ No │ No │ Update single config field │
│ DELETE │ Yes │ No │ Delete user conversation │
└─────────┴──────────────┴──────────────┴─────────────────────────────┘
* **Idempotence**: Running an operation once produces the exact same result as running it 100 times.
* **POST** is neither safe nor idempotent. Every POST to a payment processor charges the card again. Similarly, posting a prompt to an LLM provider generates tokens and incurs costs every time.Real-World Example
In Cursor:
- GET is triggered to retrieve the list of indexing files.
- POST is used when sending a prompt to the indexing pipeline, which creates a new vector embeddings search job.
- DELETE is used to remove an indexed repository.
Python Example
Here is a routing system demonstrating method execution using Python's structural pattern matching (introduced in Python 3.10):
from typing import Dict, Any
class MockAgentAPI:
"""Routing layer that routes requests based on standard HTTP verbs."""
def __init__(self):
self.agents: Dict[str, dict] = {
"agent_1": {"name": "SearchBot", "type": "researcher"}
}
def handle(self, method: str, agent_id: str, payload: dict = None) -> Dict[str, Any]:
match method.upper():
case "GET":
if agent_id in self.agents:
return {"status": "success", "data": self.agents[agent_id]}
return {"status": "error", "message": "Agent not found."}
case "POST":
# Typically used for creation
if agent_id in self.agents:
return {"status": "error", "message": "Agent already exists."}
self.agents[agent_id] = payload or {}
return {"status": "created", "data": self.agents[agent_id]}
case "PATCH":
# Partial update
if agent_id not in self.agents:
return {"status": "error", "message": "Agent not found."}
self.agents[agent_id].update(payload or {})
return {"status": "updated", "data": self.agents[agent_id]}
case "DELETE":
if agent_id in self.agents:
del self.agents[agent_id]
return {"status": "deleted"}
return {"status": "error", "message": "Agent not found."}
case _:
return {"status": "error", "message": "Method not supported."}
if __name__ == "__main__":
api = MockAgentAPI()
# Create agent_2
print(api.handle("POST", "agent_2", {"name": "CodingBot", "type": "developer"}))
# Patch agent_2
print(api.handle("PATCH", "agent_2", {"type": "architect"}))
# Fetch agent_2
print(api.handle("GET", "agent_2"))Interview Questions
- Beginner: What is the difference between GET and POST requests?
- Intermediate: What is the difference between PUT and PATCH?
- Advanced: Why do we use POST instead of GET for LLM text generation endpoints, even though we are retrieving text output?
Interview Answers
- Beginner: GET requests are used to retrieve information from a server and should not modify data. POST requests are used to submit data to the server to create a new resource or execute a stateful operation.
- Intermediate: PUT is used to replace an entire resource payload (requires sending all fields). PATCH is used to update specific fields of a resource (only the fields that are changing need to be sent).
- Advanced: We use POST because LLM generation requires sending input payloads (prompts, temperature configurations, tools) that can exceed the length limits of GET query parameters (typically 2048 characters). Additionally, generation is computational-heavy, non-deterministic, has side effects (costs tokens/credits), and should not be cached.
Common Mistakes
- GET requests with side-effects: Modifying database records inside a GET handler. This is dangerous because web crawlers, indexers, or pre-fetching tools scanning your page can trigger state changes by calling your GET routes.
Assignment
Implement a mock class showing the behavioral difference between PUT and PATCH operations on an agent configuration payload.