API Request Flow
Building an API request correctly requires setting the right method, URL, headers, and body. Each element serves a specific purpose in the communication.
8 min•By Priygop Team•Updated 2026
Building an API Request
Building an API Request
import requests
import json
def call_api(
method: str,
url: str,
params: dict = None,
data: dict = None,
headers: dict = None,
timeout: int = 10
) -> dict:
"""
Generic API caller with error handling.
Returns a structured result for the agent.
"""
try:
response = requests.request(
method=method.upper(),
url=url,
params=params, # Added to URL as ?key=value
json=data, # Sent as JSON body
headers=headers or {},
timeout=timeout
)
# Check HTTP status
if response.status_code == 200:
return {"status": "success", "data": response.json()}
elif response.status_code == 404:
return {"status": "error", "error_type": "not_found",
"error": f"Resource not found at {url}"}
elif response.status_code == 401:
return {"status": "error", "error_type": "auth",
"error": "Authentication failed. Check API key."}
elif response.status_code == 429:
retry_after = response.headers.get("Retry-After", 60)
return {"status": "error", "error_type": "rate_limit",
"error": "Rate limit exceeded",
"retry_after_seconds": int(retry_after)}
else:
return {"status": "error", "error_type": "http",
"error": f"HTTP {response.status_code}: {response.text[:200]}"}
except requests.Timeout:
return {"status": "error", "error_type": "timeout",
"error": f"Request timed out after {timeout} seconds"}
except requests.ConnectionError:
return {"status": "error", "error_type": "network",
"error": "Could not connect to the API"}
# Example: GET request with query parameters
result = call_api(
method="GET",
url="https://api.example.com/orders",
params={"customer_id": "C123", "status": "pending"},
headers={"Authorization": "Bearer YOUR_API_KEY"}
)
print(result["status"])