Files
AutoMarket/backend/flowwow_api/client.py

73 lines
3.1 KiB
Python

import os
import requests
import time
from typing import Dict, Any, Optional
from .exceptions import FlowwowAPIError, FlowwowAuthError, FlowwowRateLimitError, FlowwowBadRequestError, FlowwowNotFoundError
class FlowwowClient:
"""Base client for interacting with Flowwow API."""
BASE_URL = "https://flowwow.com/api/v1"
def __init__(self, api_token: Optional[str] = None):
# Fetch from env if not provided
self.api_token = api_token or os.getenv('FLOWWOW_API_TOKEN')
if not self.api_token:
raise ValueError("FLOWWOW_API_TOKEN must be provided")
self.session = requests.Session()
# Flowwow usually uses X-Api-Key or Authorization Bearer.
# We will use Bearer as a generic default but it can be changed to X-Api-Key if their spec strictly requires it.
self.session.headers.update({
"Authorization": f"Bearer {self.api_token}",
"Content-Type": "application/json"
})
def request(self, method: str, path: str, data: Optional[Dict[str, Any]] = None, params: Optional[Dict[str, Any]] = None, retries: int = 3) -> Dict[str, Any]:
"""Perform HTTP request to Flowwow API with automatic retries."""
url = f"{self.BASE_URL}{path}"
for attempt in range(retries):
try:
response = self.session.request(method, url, json=data, params=params)
# Check rate limiting
if response.status_code == 429:
if attempt < retries - 1:
time.sleep(2 ** attempt) # Exponential backoff
continue
raise FlowwowRateLimitError("Rate limit exceeded")
if response.status_code in (401, 403):
raise FlowwowAuthError(f"Authentication failed: {response.text}")
if response.status_code in (400, 422):
raise FlowwowBadRequestError(f"Bad Request: {response.text}")
if response.status_code == 404:
raise FlowwowNotFoundError(f"Not Found: {response.text}")
response.raise_for_status()
if response.content:
return response.json()
return {}
except requests.exceptions.RequestException as e:
if attempt < retries - 1:
time.sleep(2 ** attempt)
continue
raise FlowwowAPIError(f"Request failed: {str(e)}")
raise FlowwowAPIError("Request failed after max retries")
def post(self, path: str, data: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
return self.request("POST", path, data=data)
def get(self, path: str, params: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
return self.request("GET", path, params=params)
def put(self, path: str, data: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
return self.request("PUT", path, data=data)