Qurrah commited on
Commit
baf1217
·
1 Parent(s): 96c9cd5

ADD: implement product search API client for Shopify with product retrieval functionality

Browse files
clients/shopify/product_search_api.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+
3
+ from core.config import settings
4
+
5
+
6
+ SHOPIFY_API_VERSION = settings.shopify_api_version
7
+
8
+
9
+ def _graphql_url(shop_domain: str) -> str:
10
+ return f"https://{shop_domain}/admin/api/{SHOPIFY_API_VERSION}/graphql.json"
11
+
12
+
13
+ def _headers(access_token: str) -> dict:
14
+ return {
15
+ "X-Shopify-Access-Token": access_token,
16
+ "Content-Type": "application/json",
17
+ }
18
+
19
+
20
+ def search_products(shop_domain: str, access_token: str, search_term: str, limit: int = 5) -> list[dict]:
21
+ graphql_query = """
22
+ query searchProducts($query: String!, $limit: Int!) {
23
+ products(query: $query, first: $limit) {
24
+ edges {
25
+ node {
26
+ id
27
+ title
28
+ description
29
+ productType
30
+ tags
31
+ variants(first: 10) {
32
+ edges {
33
+ node {
34
+ title
35
+ price
36
+ inventoryQuantity
37
+ availableForSale
38
+ }
39
+ }
40
+ }
41
+ }
42
+ }
43
+ }
44
+ }
45
+ """
46
+
47
+ if not search_term.strip():
48
+ limit = 20
49
+
50
+ response = requests.post(
51
+ _graphql_url(shop_domain),
52
+ headers=_headers(access_token),
53
+ json={
54
+ "query": graphql_query,
55
+ "variables": {"query": search_term, "limit": limit},
56
+ },
57
+ )
58
+ response.raise_for_status()
59
+ data = response.json()
60
+
61
+ products = []
62
+ for edge in data.get("data", {}).get("products", {}).get("edges", []):
63
+ node = edge["node"]
64
+ variants = [
65
+ {
66
+ "title": variant["node"]["title"],
67
+ "price": variant["node"]["price"],
68
+ "stock": variant["node"]["inventoryQuantity"],
69
+ "available": variant["node"]["availableForSale"],
70
+ }
71
+ for variant in node["variants"]["edges"]
72
+ ]
73
+ products.append({
74
+ "title": node["title"],
75
+ "description": node["description"],
76
+ "product_type": node["productType"],
77
+ "tags": node["tags"],
78
+ "variants": variants,
79
+ })
80
+
81
+ return products