feat: implement backend API clients for multi-marketplace integration and frontend service layer
This commit is contained in:
15
backend/lamoda_api/__init__.py
Normal file
15
backend/lamoda_api/__init__.py
Normal file
@@ -0,0 +1,15 @@
|
||||
from .client import LamodaClient
|
||||
from .services.products import ProductsService
|
||||
from .services.orders import OrdersService
|
||||
|
||||
class LamodaAPI:
|
||||
"""
|
||||
Main entry point for Lamoda Seller Partner SDK.
|
||||
Instantiates all services with a shared client.
|
||||
"""
|
||||
def __init__(self, api_key: str = None):
|
||||
self.client = LamodaClient(api_key)
|
||||
|
||||
# Initialize services
|
||||
self.products = ProductsService(self.client)
|
||||
self.orders = OrdersService(self.client)
|
||||
72
backend/lamoda_api/client.py
Normal file
72
backend/lamoda_api/client.py
Normal file
@@ -0,0 +1,72 @@
|
||||
import os
|
||||
import requests
|
||||
import time
|
||||
from typing import Dict, Any, Optional
|
||||
from .exceptions import LamodaAPIError, LamodaAuthError, LamodaRateLimitError, LamodaBadRequestError, LamodaNotFoundError
|
||||
|
||||
class LamodaClient:
|
||||
"""Base client for interacting with Lamoda Seller Partner API."""
|
||||
|
||||
BASE_URL = "https://api.seller.lamoda.ru"
|
||||
|
||||
def __init__(self, api_key: Optional[str] = None):
|
||||
# Fetch from env if not provided
|
||||
self.api_key = api_key or os.getenv('LAMODA_API_KEY')
|
||||
|
||||
if not self.api_key:
|
||||
raise ValueError("LAMODA_API_KEY must be provided")
|
||||
|
||||
self.session = requests.Session()
|
||||
# Lamoda often uses X-API-Key or Authorization Bearer depending on the endpoint.
|
||||
# We assume X-API-Key as the standard for B2B API integrations.
|
||||
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 Lamoda 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 LamodaRateLimitError("Rate limit exceeded")
|
||||
|
||||
if response.status_code in (401, 403):
|
||||
raise LamodaAuthError(f"Authentication failed: {response.text}")
|
||||
|
||||
if response.status_code == 400:
|
||||
raise LamodaBadRequestError(f"Bad Request: {response.text}")
|
||||
|
||||
if response.status_code == 404:
|
||||
raise LamodaNotFoundError(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 LamodaAPIError(f"Request failed: {str(e)}")
|
||||
|
||||
raise LamodaAPIError("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/lamoda_api/exceptions.py
Normal file
19
backend/lamoda_api/exceptions.py
Normal file
@@ -0,0 +1,19 @@
|
||||
class LamodaAPIError(Exception):
|
||||
"""Base exception for all Lamoda API errors."""
|
||||
pass
|
||||
|
||||
class LamodaAuthError(LamodaAPIError):
|
||||
"""Raised when authentication fails (HTTP 401 or 403)."""
|
||||
pass
|
||||
|
||||
class LamodaRateLimitError(LamodaAPIError):
|
||||
"""Raised when API rate limits are exceeded (HTTP 429)."""
|
||||
pass
|
||||
|
||||
class LamodaBadRequestError(LamodaAPIError):
|
||||
"""Raised when API returns HTTP 400."""
|
||||
pass
|
||||
|
||||
class LamodaNotFoundError(LamodaAPIError):
|
||||
"""Raised when API returns HTTP 404."""
|
||||
pass
|
||||
22
backend/lamoda_api/services/orders.py
Normal file
22
backend/lamoda_api/services/orders.py
Normal file
@@ -0,0 +1,22 @@
|
||||
from typing import Dict, Any, List
|
||||
from ..client import LamodaClient
|
||||
|
||||
class OrdersService:
|
||||
"""Service to handle Lamoda Orders (FBS)."""
|
||||
|
||||
def __init__(self, client: LamodaClient):
|
||||
self.client = client
|
||||
|
||||
def get_new_orders(self, limit: int = 100) -> Dict[str, Any]:
|
||||
"""
|
||||
Get list of new orders (assembly tasks).
|
||||
Endpoint: /v1/orders/new
|
||||
"""
|
||||
return self.client.get("/v1/orders/new", params={"limit": limit})
|
||||
|
||||
def confirm_packaging(self, order_ids: List[str]) -> Dict[str, Any]:
|
||||
"""
|
||||
Confirm that orders are packaged and ready for dispatch.
|
||||
Endpoint: /v1/orders/pack
|
||||
"""
|
||||
return self.client.post("/v1/orders/pack", data={"order_ids": order_ids})
|
||||
31
backend/lamoda_api/services/products.py
Normal file
31
backend/lamoda_api/services/products.py
Normal file
@@ -0,0 +1,31 @@
|
||||
from typing import Dict, Any, List
|
||||
from ..client import LamodaClient
|
||||
|
||||
class ProductsService:
|
||||
"""Service to handle Lamoda Products/Assortment."""
|
||||
|
||||
def __init__(self, client: LamodaClient):
|
||||
self.client = client
|
||||
|
||||
def get_list(self, limit: int = 100, offset: int = 0, **filters) -> Dict[str, Any]:
|
||||
"""
|
||||
Get list of products in the seller's catalog.
|
||||
Endpoint: /v1/products
|
||||
"""
|
||||
params = {"limit": limit, "offset": offset}
|
||||
params.update(filters)
|
||||
return self.client.get("/v1/products", params=params)
|
||||
|
||||
def update_stocks(self, items: List[Dict[str, Any]]) -> Dict[str, Any]:
|
||||
"""
|
||||
Update stock levels (FBS).
|
||||
Endpoint: /v1/stocks
|
||||
"""
|
||||
return self.client.post("/v1/stocks", data={"stocks": items})
|
||||
|
||||
def update_prices(self, items: List[Dict[str, Any]]) -> Dict[str, Any]:
|
||||
"""
|
||||
Update prices for products.
|
||||
Endpoint: /v1/prices
|
||||
"""
|
||||
return self.client.post("/v1/prices", data={"prices": items})
|
||||
Reference in New Issue
Block a user