feat: implement backend API clients for multi-marketplace integration and frontend service layer
This commit is contained in:
15
backend/ym_api/__init__.py
Normal file
15
backend/ym_api/__init__.py
Normal file
@@ -0,0 +1,15 @@
|
||||
from .client import YMClient
|
||||
from .services.orders import OrdersService
|
||||
from .services.assortment import AssortmentService
|
||||
|
||||
class YandexMarketAPI:
|
||||
"""
|
||||
Main entry point for Yandex Market SDK.
|
||||
Instantiates all services with a shared client.
|
||||
"""
|
||||
def __init__(self, api_token: str = None, campaign_id: str = None, business_id: str = None):
|
||||
self.client = YMClient(api_token, campaign_id, business_id)
|
||||
|
||||
# Initialize services
|
||||
self.orders = OrdersService(self.client)
|
||||
self.assortment = AssortmentService(self.client)
|
||||
75
backend/ym_api/client.py
Normal file
75
backend/ym_api/client.py
Normal file
@@ -0,0 +1,75 @@
|
||||
import os
|
||||
import requests
|
||||
import time
|
||||
from typing import Dict, Any, Optional
|
||||
from .exceptions import YMAPIError, YMAuthError, YMRateLimitError, YMBadRequestError, YMNotFoundError
|
||||
|
||||
class YMClient:
|
||||
"""Base client for interacting with Yandex Market API."""
|
||||
|
||||
BASE_URL = "https://api.partner.market.yandex.ru/v2"
|
||||
|
||||
def __init__(self, api_token: Optional[str] = None, campaign_id: Optional[str] = None, business_id: Optional[str] = None):
|
||||
# Fetch from env if not provided
|
||||
self.api_token = api_token or os.getenv('YM_API_TOKEN')
|
||||
self.campaign_id = campaign_id or os.getenv('YM_CAMPAIGN_ID')
|
||||
self.business_id = business_id or os.getenv('YM_BUSINESS_ID')
|
||||
|
||||
if not self.api_token:
|
||||
raise ValueError("YM_API_TOKEN must be provided")
|
||||
|
||||
self.session = requests.Session()
|
||||
|
||||
# Depending on app type, token might be Bearer or OAuth oauth_token=...
|
||||
# We will use Bearer as it's the modern standard for YM API
|
||||
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 Yandex Market 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 YMRateLimitError("Rate limit exceeded")
|
||||
|
||||
if response.status_code in (401, 403):
|
||||
raise YMAuthError(f"Authentication failed: {response.text}")
|
||||
|
||||
if response.status_code == 400:
|
||||
raise YMBadRequestError(f"Bad Request: {response.text}")
|
||||
|
||||
if response.status_code == 404:
|
||||
raise YMNotFoundError(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 YMAPIError(f"Request failed: {str(e)}")
|
||||
|
||||
raise YMAPIError("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)
|
||||
19
backend/ym_api/exceptions.py
Normal file
19
backend/ym_api/exceptions.py
Normal file
@@ -0,0 +1,19 @@
|
||||
class YMAPIError(Exception):
|
||||
"""Base exception for all Yandex Market API errors."""
|
||||
pass
|
||||
|
||||
class YMAuthError(YMAPIError):
|
||||
"""Raised when authentication fails (HTTP 401 or 403)."""
|
||||
pass
|
||||
|
||||
class YMRateLimitError(YMAPIError):
|
||||
"""Raised when API rate limits are exceeded (HTTP 429)."""
|
||||
pass
|
||||
|
||||
class YMBadRequestError(YMAPIError):
|
||||
"""Raised when API returns HTTP 400 (Bad Request)."""
|
||||
pass
|
||||
|
||||
class YMNotFoundError(YMAPIError):
|
||||
"""Raised when API returns HTTP 404 (Not Found)."""
|
||||
pass
|
||||
34
backend/ym_api/services/assortment.py
Normal file
34
backend/ym_api/services/assortment.py
Normal file
@@ -0,0 +1,34 @@
|
||||
from typing import Dict, Any, List, Optional
|
||||
from ..client import YMClient
|
||||
|
||||
class AssortmentService:
|
||||
"""Service to handle Yandex Market Assortment/Products."""
|
||||
|
||||
def __init__(self, client: YMClient):
|
||||
self.client = client
|
||||
|
||||
def get_offer_mappings(self, business_id: Optional[str] = None, page_token: str = None, limit: int = 100) -> Dict[str, Any]:
|
||||
"""
|
||||
Get list of offers (products) in the business catalog.
|
||||
Endpoint: /businesses/{businessId}/offer-mappings.json
|
||||
"""
|
||||
bid = business_id or self.client.business_id
|
||||
if not bid:
|
||||
raise ValueError("business_id must be provided either in the method call or client initialization.")
|
||||
|
||||
payload = {"limit": limit}
|
||||
if page_token:
|
||||
payload["page_token"] = page_token
|
||||
|
||||
return self.client.post(f"/businesses/{bid}/offer-mappings.json", data=payload)
|
||||
|
||||
def update_offer_mappings(self, offers: List[Dict[str, Any]], business_id: Optional[str] = None) -> Dict[str, Any]:
|
||||
"""
|
||||
Update offers (products) in the business catalog.
|
||||
Endpoint: /businesses/{businessId}/offer-mappings/update.json
|
||||
"""
|
||||
bid = business_id or self.client.business_id
|
||||
if not bid:
|
||||
raise ValueError("business_id must be provided either in the method call or client initialization.")
|
||||
|
||||
return self.client.post(f"/businesses/{bid}/offer-mappings/update.json", data={"offerMappings": offers})
|
||||
45
backend/ym_api/services/orders.py
Normal file
45
backend/ym_api/services/orders.py
Normal file
@@ -0,0 +1,45 @@
|
||||
from typing import Dict, Any, Optional
|
||||
from ..client import YMClient
|
||||
|
||||
class OrdersService:
|
||||
"""Service to handle Yandex Market Orders."""
|
||||
|
||||
def __init__(self, client: YMClient):
|
||||
self.client = client
|
||||
|
||||
def get_list(self, campaign_id: Optional[str] = None, params: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
|
||||
"""
|
||||
Get list of orders for a specific campaign.
|
||||
Endpoint: /campaigns/{campaignId}/orders.json
|
||||
"""
|
||||
cid = campaign_id or self.client.campaign_id
|
||||
if not cid:
|
||||
raise ValueError("campaign_id must be provided either in the method call or client initialization.")
|
||||
|
||||
return self.client.get(f"/campaigns/{cid}/orders.json", params=params)
|
||||
|
||||
def get_order(self, order_id: str, campaign_id: Optional[str] = None) -> Dict[str, Any]:
|
||||
"""
|
||||
Get info about a specific order.
|
||||
Endpoint: /campaigns/{campaignId}/orders/{orderId}.json
|
||||
"""
|
||||
cid = campaign_id or self.client.campaign_id
|
||||
if not cid:
|
||||
raise ValueError("campaign_id must be provided either in the method call or client initialization.")
|
||||
|
||||
return self.client.get(f"/campaigns/{cid}/orders/{order_id}.json")
|
||||
|
||||
def update_status(self, order_id: str, status: str, substatus: Optional[str] = None, campaign_id: Optional[str] = None) -> Dict[str, Any]:
|
||||
"""
|
||||
Update the status of an order.
|
||||
Endpoint: /campaigns/{campaignId}/orders/{orderId}/status.json
|
||||
"""
|
||||
cid = campaign_id or self.client.campaign_id
|
||||
if not cid:
|
||||
raise ValueError("campaign_id must be provided either in the method call or client initialization.")
|
||||
|
||||
payload = {"order": {"status": status}}
|
||||
if substatus:
|
||||
payload["order"]["substatus"] = substatus
|
||||
|
||||
return self.client.put(f"/campaigns/{cid}/orders/{order_id}/status.json", data=payload)
|
||||
Reference in New Issue
Block a user