import requests
import time
def search_with_retry(query, api_key, max_retries=3):
url = "https://api.trackyard.com/api/external/v1/search"
headers = {"Authorization": f"Bearer {api_key}"}
for attempt in range(max_retries):
response = requests.post(url, headers=headers, json={"query": query})
# Success
if response.status_code == 200:
return response.json()
# Rate limit - wait and retry
if response.status_code == 429:
retry_after = int(response.headers.get("Retry-After", 60))
print(f"Rate limited. Retrying in {retry_after}s...")
time.sleep(retry_after)
continue
# Out of credits - stop immediately
if response.status_code == 402:
raise Exception("Out of credits. Please upgrade your plan.")
# Other errors
error = response.json()
raise Exception(f"API error: {error.get('error')} (code: {error.get('code')})")
raise Exception("Max retries exceeded")