feat: implement backend API clients for multi-marketplace integration and frontend service layer
This commit is contained in:
15
backend/ozon_api/__init__.py
Normal file
15
backend/ozon_api/__init__.py
Normal file
@@ -0,0 +1,15 @@
|
||||
from .client import OzonClient
|
||||
from .services.products import ProductsService
|
||||
from .services.fbs import FBSService
|
||||
|
||||
class OzonAPI:
|
||||
"""
|
||||
Main entry point for Ozon SDK.
|
||||
Instantiates all services with a shared client.
|
||||
"""
|
||||
def __init__(self, client_id: str = None, api_key: str = None):
|
||||
self.client = OzonClient(client_id, api_key)
|
||||
|
||||
# Initialize services
|
||||
self.products = ProductsService(self.client)
|
||||
self.fbs = FBSService(self.client)
|
||||
68
backend/ozon_api/client.py
Normal file
68
backend/ozon_api/client.py
Normal file
@@ -0,0 +1,68 @@
|
||||
import os
|
||||
import requests
|
||||
import time
|
||||
from typing import Dict, Any, Optional
|
||||
from .exceptions import OzonAPIError, OzonAuthError, OzonRateLimitError, OzonBadRequestError
|
||||
|
||||
class OzonClient:
|
||||
"""Base client for interacting with Ozon API."""
|
||||
|
||||
BASE_URL = "https://api-seller.ozon.ru"
|
||||
|
||||
def __init__(self, client_id: Optional[str] = None, api_key: Optional[str] = None):
|
||||
# Fetch from env if not provided
|
||||
self.client_id = client_id or os.getenv('OZON_CLIENT_ID')
|
||||
self.api_key = api_key or os.getenv('OZON_API_KEY')
|
||||
|
||||
if not self.client_id or not self.api_key:
|
||||
raise ValueError("OZON_CLIENT_ID and OZON_API_KEY must be provided")
|
||||
|
||||
self.session = requests.Session()
|
||||
self.session.headers.update({
|
||||
"Client-Id": self.client_id,
|
||||
"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 Ozon 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 OzonRateLimitError("Rate limit exceeded")
|
||||
|
||||
if response.status_code in (401, 403):
|
||||
raise OzonAuthError(f"Authentication failed: {response.text}")
|
||||
|
||||
if response.status_code == 400:
|
||||
raise OzonBadRequestError(f"Bad Request: {response.text}")
|
||||
|
||||
response.raise_for_status()
|
||||
|
||||
# Ozon usually wraps responses in "result" key, but not always.
|
||||
# We return the whole JSON parsed response.
|
||||
if response.content:
|
||||
return response.json()
|
||||
return {}
|
||||
|
||||
except requests.exceptions.RequestException as e:
|
||||
if attempt < retries - 1:
|
||||
time.sleep(2 ** attempt)
|
||||
continue
|
||||
raise OzonAPIError(f"Request failed: {str(e)}")
|
||||
|
||||
raise OzonAPIError("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)
|
||||
15
backend/ozon_api/exceptions.py
Normal file
15
backend/ozon_api/exceptions.py
Normal file
@@ -0,0 +1,15 @@
|
||||
class OzonAPIError(Exception):
|
||||
"""Base exception for all Ozon API errors."""
|
||||
pass
|
||||
|
||||
class OzonAuthError(OzonAPIError):
|
||||
"""Raised when authentication fails (e.g. invalid Client-Id or Api-Key)."""
|
||||
pass
|
||||
|
||||
class OzonRateLimitError(OzonAPIError):
|
||||
"""Raised when API rate limits are exceeded (HTTP 429)."""
|
||||
pass
|
||||
|
||||
class OzonBadRequestError(OzonAPIError):
|
||||
"""Raised when API returns HTTP 400 (Bad Request)."""
|
||||
pass
|
||||
33
backend/ozon_api/services/fbs.py
Normal file
33
backend/ozon_api/services/fbs.py
Normal file
@@ -0,0 +1,33 @@
|
||||
from typing import Dict, Any, List
|
||||
from ..client import OzonClient
|
||||
|
||||
class FBSService:
|
||||
"""Service to handle FBS (Fulfillment by Seller) operations."""
|
||||
|
||||
def __init__(self, client: OzonClient):
|
||||
self.client = client
|
||||
|
||||
def get_unfulfilled_list(self, dir: str = "ASC", filter_params: Dict[str, Any] = None, limit: int = 100, offset: int = 0) -> Dict[str, Any]:
|
||||
"""
|
||||
Get a list of new/unfulfilled FBS orders.
|
||||
Endpoint: /v3/posting/fbs/unfulfilled/list
|
||||
"""
|
||||
payload = {
|
||||
"dir": dir,
|
||||
"filter": filter_params or {},
|
||||
"limit": limit,
|
||||
"offset": offset,
|
||||
"with": {
|
||||
"analytics_data": True,
|
||||
"barcodes": True,
|
||||
"financial_data": True
|
||||
}
|
||||
}
|
||||
return self.client.post("/v3/posting/fbs/unfulfilled/list", data=payload)
|
||||
|
||||
def ship_packages(self, packages: List[Dict[str, Any]]) -> Dict[str, Any]:
|
||||
"""
|
||||
Ship unfulfilled orders.
|
||||
Endpoint: /v3/posting/fbs/ship
|
||||
"""
|
||||
return self.client.post("/v3/posting/fbs/ship", data={"packages": packages})
|
||||
42
backend/ozon_api/services/products.py
Normal file
42
backend/ozon_api/services/products.py
Normal file
@@ -0,0 +1,42 @@
|
||||
from typing import Dict, Any, List
|
||||
from ..client import OzonClient
|
||||
|
||||
class ProductsService:
|
||||
"""Service to handle product-related operations."""
|
||||
|
||||
def __init__(self, client: OzonClient):
|
||||
self.client = client
|
||||
|
||||
def get_list(self, filter_params: Dict[str, Any] = None, last_id: str = "", limit: int = 100) -> Dict[str, Any]:
|
||||
"""
|
||||
Get a list of products.
|
||||
Endpoint: /v2/product/list
|
||||
"""
|
||||
payload = {
|
||||
"filter": filter_params or {},
|
||||
"last_id": last_id,
|
||||
"limit": limit
|
||||
}
|
||||
return self.client.post("/v2/product/list", data=payload)
|
||||
|
||||
def get_info(self, offer_id: str = None, product_id: int = None, sku: int = None) -> Dict[str, Any]:
|
||||
"""
|
||||
Get product info by offer_id, product_id or sku.
|
||||
Endpoint: /v2/product/info
|
||||
"""
|
||||
payload = {}
|
||||
if offer_id:
|
||||
payload["offer_id"] = offer_id
|
||||
if product_id:
|
||||
payload["product_id"] = product_id
|
||||
if sku:
|
||||
payload["sku"] = sku
|
||||
|
||||
return self.client.post("/v2/product/info", data=payload)
|
||||
|
||||
def import_products(self, items: List[Dict[str, Any]]) -> Dict[str, Any]:
|
||||
"""
|
||||
Create or update products.
|
||||
Endpoint: /v2/product/import
|
||||
"""
|
||||
return self.client.post("/v2/product/import", data={"items": items})
|
||||
Reference in New Issue
Block a user