Spaces:
Sleeping
Sleeping
ADD: implement Shopify API client with product and policy retrieval functions
Browse files- clients/shopify/admin_api.py +149 -0
clients/shopify/admin_api.py
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
|
| 3 |
+
import requests
|
| 4 |
+
from bs4 import BeautifulSoup
|
| 5 |
+
from requests.adapters import HTTPAdapter
|
| 6 |
+
from urllib3.util.retry import Retry
|
| 7 |
+
|
| 8 |
+
from core.config import settings
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
logger = logging.getLogger(__name__)
|
| 12 |
+
|
| 13 |
+
SHOPIFY_API_VERSION = settings.shopify_api_version
|
| 14 |
+
TIMEOUT = (5, 30)
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def _make_session() -> requests.Session:
|
| 18 |
+
session = requests.Session()
|
| 19 |
+
retry = Retry(
|
| 20 |
+
total=3,
|
| 21 |
+
backoff_factor=1,
|
| 22 |
+
status_forcelist=[429, 500, 502, 503, 504],
|
| 23 |
+
allowed_methods=["GET"],
|
| 24 |
+
)
|
| 25 |
+
adapter = HTTPAdapter(max_retries=retry)
|
| 26 |
+
session.mount("https://", adapter)
|
| 27 |
+
return session
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
_session = _make_session()
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def _headers(access_token: str) -> dict:
|
| 34 |
+
return {"X-Shopify-Access-Token": access_token}
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def _base_url(shop_domain: str) -> str:
|
| 38 |
+
return f"https://{shop_domain}/admin/api/{SHOPIFY_API_VERSION}"
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def _strip_html(html: str) -> str:
|
| 42 |
+
if not html:
|
| 43 |
+
return ""
|
| 44 |
+
return BeautifulSoup(html, "html.parser").get_text(separator=" ").strip()
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def get_shop_info(shop_domain: str, access_token: str) -> dict:
|
| 48 |
+
url = f"{_base_url(shop_domain)}/shop.json"
|
| 49 |
+
res = _session.get(url, headers=_headers(access_token), timeout=TIMEOUT)
|
| 50 |
+
res.raise_for_status()
|
| 51 |
+
return res.json()["shop"]
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def get_products(shop_domain: str, access_token: str, workspace_id: str) -> list[dict]:
|
| 55 |
+
url = f"{_base_url(shop_domain)}/products.json"
|
| 56 |
+
params = {"limit": 250}
|
| 57 |
+
products = []
|
| 58 |
+
|
| 59 |
+
while url:
|
| 60 |
+
res = _session.get(url, headers=_headers(access_token), params=params, timeout=TIMEOUT)
|
| 61 |
+
res.raise_for_status()
|
| 62 |
+
data = res.json()
|
| 63 |
+
products.extend(data.get("products", []))
|
| 64 |
+
|
| 65 |
+
link = res.headers.get("Link", "")
|
| 66 |
+
url = None
|
| 67 |
+
params = {}
|
| 68 |
+
if 'rel="next"' in link:
|
| 69 |
+
for part in link.split(","):
|
| 70 |
+
if 'rel="next"' in part:
|
| 71 |
+
url = part.split(";")[0].strip().strip("<>")
|
| 72 |
+
|
| 73 |
+
result = []
|
| 74 |
+
for product in products:
|
| 75 |
+
sizes = list({v["option1"] for v in product["variants"] if v.get("option1")})
|
| 76 |
+
colors = list({v["option2"] for v in product["variants"] if v.get("option2")})
|
| 77 |
+
|
| 78 |
+
attributes = {}
|
| 79 |
+
if sizes:
|
| 80 |
+
attributes["sizes"] = sizes
|
| 81 |
+
if colors:
|
| 82 |
+
attributes["colors"] = colors
|
| 83 |
+
|
| 84 |
+
tags = [tag.strip() for tag in product.get("tags", "").split(",") if tag.strip()]
|
| 85 |
+
if tags:
|
| 86 |
+
attributes["tags"] = tags
|
| 87 |
+
|
| 88 |
+
result.append({
|
| 89 |
+
"id": str(product["id"]),
|
| 90 |
+
"workspace_id": workspace_id,
|
| 91 |
+
"name": product["title"],
|
| 92 |
+
"description": _strip_html(product.get("body_html", "")),
|
| 93 |
+
"category": product.get("product_type", ""),
|
| 94 |
+
"base_price": float(product["variants"][0]["price"]) if product["variants"] else 0.0,
|
| 95 |
+
"attributes": attributes,
|
| 96 |
+
})
|
| 97 |
+
|
| 98 |
+
logger.info(f"Pulled {len(result)} products from Shopify")
|
| 99 |
+
return result
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def get_policies(shop_domain: str, access_token: str, workspace_id: str) -> list[dict]:
|
| 103 |
+
url = f"{_base_url(shop_domain)}/policies.json"
|
| 104 |
+
res = _session.get(url, headers=_headers(access_token), timeout=TIMEOUT)
|
| 105 |
+
res.raise_for_status()
|
| 106 |
+
|
| 107 |
+
policies = res.json().get("policies", [])
|
| 108 |
+
result = []
|
| 109 |
+
|
| 110 |
+
for policy in policies:
|
| 111 |
+
if not policy.get("body"):
|
| 112 |
+
continue
|
| 113 |
+
result.append({
|
| 114 |
+
"id": policy["handle"],
|
| 115 |
+
"workspace_id": workspace_id,
|
| 116 |
+
"type": policy["handle"],
|
| 117 |
+
"title": policy["title"],
|
| 118 |
+
"content": _strip_html(policy["body"]),
|
| 119 |
+
})
|
| 120 |
+
|
| 121 |
+
logger.info(f"Pulled {len(result)} policies from Shopify")
|
| 122 |
+
return result
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def get_inventory(shop_domain: str, access_token: str, query: str = None) -> str:
|
| 126 |
+
url = f"{_base_url(shop_domain)}/products.json"
|
| 127 |
+
params = {"limit": 250}
|
| 128 |
+
|
| 129 |
+
if query:
|
| 130 |
+
params["title"] = query
|
| 131 |
+
|
| 132 |
+
res = _session.get(url, headers=_headers(access_token), params=params, timeout=TIMEOUT)
|
| 133 |
+
res.raise_for_status()
|
| 134 |
+
products = res.json().get("products", [])
|
| 135 |
+
|
| 136 |
+
if not products:
|
| 137 |
+
return "No matching products found in inventory."
|
| 138 |
+
|
| 139 |
+
lines = []
|
| 140 |
+
for product in products:
|
| 141 |
+
lines.append(f"\nProduct: {product['title']} ({product.get('product_type', '')})")
|
| 142 |
+
for variant in product["variants"]:
|
| 143 |
+
status = "In Stock" if variant["inventory_quantity"] > 0 else "Out of Stock"
|
| 144 |
+
lines.append(
|
| 145 |
+
f" - {variant['title']} | Price: ${variant['price']} | "
|
| 146 |
+
f"Stock: {variant['inventory_quantity']} | {status}"
|
| 147 |
+
)
|
| 148 |
+
|
| 149 |
+
return "\n".join(lines)
|