File size: 9,084 Bytes
7235b12 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 | """
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()
|