portable-devtools / bin /api_call.py
codekingpro's picture
Add files using upload-large-folder tool
7235b12 verified
Raw
History Blame Contribute Delete
9.08 kB
"""
World-Level API Resilience Toolkit
====================================
Handles: IP blocks, timeouts, rate limits, SSL errors, connection drops
Usage:
python api_call.py GET https://api.example.com/endpoint
python api_call.py POST https://api.example.com/data '{"key":"value"}'
python api_call.py GET https://api.example.com --proxy http://127.0.0.1:8080
Features:
- Auto Retry with Exponential Backoff
- Random User-Agent Rotation
- Connection Timeout Handling
- Rate Limit Detection (429) with Auto-Wait
- SSL Error Bypass Option
- Proxy Support (for mitmproxy or any proxy)
- Detailed Error Diagnosis
"""
import sys
import time
import random
import json
import urllib.request
import urllib.error
import urllib.parse
import ssl
import os
# ─────────────────────────────────────────────
# CONFIGURATION - Edit these as needed
# ─────────────────────────────────────────────
MAX_RETRIES = 5
INITIAL_WAIT = 2 # seconds before first retry
TIMEOUT = 30 # request timeout in seconds
BYPASS_SSL = False # Set True if getting SSL errors (self-signed certs)
PROXY = None # e.g. "http://127.0.0.1:8080" for mitmproxy
# ─────────────────────────────────────────────
USER_AGENTS = [
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/124.0 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:125.0) Gecko/20100101 Firefox/125.0",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 Safari/605.1.15",
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 Chrome/122.0 Safari/537.36",
"python-httpx/0.27.0",
"axios/1.7.2",
"curl/8.7.1",
]
DIAGNOSABLE_ERRORS = {
400: "BAD REQUEST - Check your payload/params format",
401: "UNAUTHORIZED - Check your API key/token",
403: "FORBIDDEN - IP may be blocked or permissions missing",
404: "NOT FOUND - Check the URL/endpoint",
408: "REQUEST TIMEOUT - Server too slow, try increasing TIMEOUT",
429: "RATE LIMITED - Waiting before retry...",
500: "SERVER ERROR - Their problem, will retry",
502: "BAD GATEWAY - Proxy/CDN issue, retrying",
503: "SERVICE UNAVAILABLE - Server overloaded, retrying",
504: "GATEWAY TIMEOUT - Network issue, retrying",
}
def make_request(method, url, data=None, headers=None, proxy=None, bypass_ssl=False, timeout=30):
"""Core request function with all resilience features."""
if headers is None:
headers = {}
headers["User-Agent"] = random.choice(USER_AGENTS)
headers["Accept"] = "application/json, text/plain, */*"
headers["Accept-Language"] = "en-US,en;q=0.9"
headers["Connection"] = "keep-alive"
# SSL context
ctx = ssl.create_default_context()
if bypass_ssl:
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
# Proxy handler
handlers = []
if proxy:
proxy_handler = urllib.request.ProxyHandler({"http": proxy, "https": proxy})
handlers.append(proxy_handler)
https_handler = urllib.request.HTTPSHandler(context=ctx)
handlers.append(https_handler)
opener = urllib.request.build_opener(*handlers)
# Build request
body = None
if data:
if isinstance(data, dict):
body = json.dumps(data).encode("utf-8")
headers["Content-Type"] = "application/json"
else:
body = data.encode("utf-8") if isinstance(data, str) else data
req = urllib.request.Request(url, data=body, headers=headers, method=method.upper())
response = opener.open(req, timeout=timeout)
raw = response.read()
status = response.status
try:
result = json.loads(raw)
except Exception:
result = raw.decode("utf-8", errors="replace")
return status, result
def api_call(method, url, data=None, headers=None):
"""Resilient API call with retry, backoff, and diagnosis."""
wait = INITIAL_WAIT
last_error = None
for attempt in range(1, MAX_RETRIES + 1):
try:
print(f"\n[Attempt {attempt}/{MAX_RETRIES}] {method.upper()} {url}")
status, result = make_request(
method, url, data=data, headers=headers,
proxy=PROXY, bypass_ssl=BYPASS_SSL, timeout=TIMEOUT
)
if status == 429:
retry_after = wait * 3
print(f" âš  {DIAGNOSABLE_ERRORS[429]}")
print(f" Waiting {retry_after}s before next attempt...")
time.sleep(retry_after)
wait = min(wait * 2, 120)
continue
if 200 <= status < 300:
print(f" ✓ SUCCESS ({status})")
return status, result
msg = DIAGNOSABLE_ERRORS.get(status, f"HTTP {status} - Unexpected error")
print(f" ✗ {msg}")
if status in (400, 401, 403, 404):
print(" → Non-retryable error. Stopping.")
return status, result
except urllib.error.URLError as e:
reason = str(e.reason)
print(f" ✗ CONNECTION ERROR: {reason}")
if "SSL" in reason or "certificate" in reason.lower():
print(" DIAGNOSIS: SSL/Certificate issue.")
print(" FIX: Set BYPASS_SSL = True in this script")
elif "timed out" in reason.lower():
print(" DIAGNOSIS: Connection timed out.")
print(" FIX: Increase TIMEOUT or check network")
elif "Name or service not known" in reason or "getaddrinfo" in reason:
print(" DIAGNOSIS: DNS resolution failed.")
print(" FIX: Check internet / try a different DNS (1.1.1.1)")
else:
print(" DIAGNOSIS: Network/connectivity issue.")
print(" FIX: Try mitmproxy or a proxy for routing")
last_error = e
except TimeoutError:
print(f" ✗ TIMEOUT after {TIMEOUT}s")
last_error = "Timeout"
except Exception as e:
print(f" ✗ UNEXPECTED: {e}")
last_error = e
if attempt < MAX_RETRIES:
print(f" ↻ Retrying in {wait}s... (backoff)")
time.sleep(wait)
wait = min(wait * 2, 60)
print(f"\n✗ All {MAX_RETRIES} attempts failed. Last error: {last_error}")
return None, None
def main():
if len(sys.argv) < 3:
print("Usage: python api_call.py <METHOD> <URL> [JSON_BODY] [--proxy PROXY_URL]")
print("Examples:")
print(" python api_call.py GET https://httpbin.org/get")
print(" python api_call.py POST https://httpbin.org/post '{\"key\":\"value\"}'")
print(" python api_call.py GET https://api.github.com/repos/cli/cli --proxy http://127.0.0.1:8080")
sys.exit(1)
method = sys.argv[1]
url = sys.argv[2]
data = None
global PROXY
args = sys.argv[3:]
for i, arg in enumerate(args):
if arg == "--proxy" and i + 1 < len(args):
PROXY = args[i + 1]
elif arg.startswith("{") or arg.startswith("["):
try:
data = json.loads(arg)
except Exception:
data = arg
status, result = api_call(method, url, data=data)
if result is not None:
print("\n─── RESPONSE ─────────────────────────────")
if isinstance(result, (dict, list)):
print(json.dumps(result, indent=2, ensure_ascii=False))
else:
print(result)
print("─────────────────────────────────────────")
if __name__ == "__main__":
main()