feat: implement backend API clients for multi-marketplace integration and frontend service layer
This commit is contained in:
67
backend/mm_api/client.py
Normal file
67
backend/mm_api/client.py
Normal file
@@ -0,0 +1,67 @@
|
||||
import os
|
||||
import requests
|
||||
import time
|
||||
from typing import Dict, Any, Optional
|
||||
from .exceptions import MMAPIError, MMAuthError, MMRateLimitError, MMBadRequestError, MMNotFoundError
|
||||
|
||||
class MMClient:
|
||||
"""Base client for interacting with Magnit Market API."""
|
||||
|
||||
BASE_URL = "https://b2b-api.magnit.ru"
|
||||
|
||||
def __init__(self, api_key: Optional[str] = None):
|
||||
# Fetch from env if not provided
|
||||
self.api_key = api_key or os.getenv('MM_API_KEY')
|
||||
|
||||
if not self.api_key:
|
||||
raise ValueError("MM_API_KEY must be provided")
|
||||
|
||||
self.session = requests.Session()
|
||||
self.session.headers.update({
|
||||
"X-Api-Key": self.api_key,
|
||||
"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 MM 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 MMRateLimitError("Rate limit exceeded")
|
||||
|
||||
if response.status_code in (401, 403):
|
||||
raise MMAuthError(f"Authentication failed: {response.text}")
|
||||
|
||||
if response.status_code == 400:
|
||||
raise MMBadRequestError(f"Bad Request: {response.text}")
|
||||
|
||||
if response.status_code == 404:
|
||||
raise MMNotFoundError(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 MMAPIError(f"Request failed: {str(e)}")
|
||||
|
||||
raise MMAPIError("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)
|
||||
Reference in New Issue
Block a user