shopifyql 0.1.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
shopifyql/__init__.py ADDED
@@ -0,0 +1,20 @@
1
+ from .auth import ShopifyAuthenticator
2
+ from .client import ShopifyQLClient
3
+ from .limiter import FixedWindowConfig, FixedWindowRateLimiter
4
+ from .results import (
5
+ ShopifyQLPandasResult,
6
+ ShopifyQLPolarsResult,
7
+ ShopifyQLRecordsResult,
8
+ ShopifyQLResult,
9
+ )
10
+
11
+ __all__ = [
12
+ "ShopifyQLClient",
13
+ "ShopifyAuthenticator",
14
+ "ShopifyQLResult",
15
+ "ShopifyQLRecordsResult",
16
+ "ShopifyQLPandasResult",
17
+ "ShopifyQLPolarsResult",
18
+ "FixedWindowRateLimiter",
19
+ "FixedWindowConfig",
20
+ ]
shopifyql/auth.py ADDED
@@ -0,0 +1,175 @@
1
+ import logging
2
+ import os
3
+ import webbrowser
4
+ from http.server import BaseHTTPRequestHandler, HTTPServer
5
+ from urllib.parse import parse_qs, urlencode, urlparse
6
+
7
+ import requests
8
+
9
+ logger = logging.getLogger(__name__)
10
+
11
+ DEFAULT_AUTO_CLOSE_DELAY = 2
12
+ HTML_AUTH_SUCCESS = """
13
+ <!DOCTYPE html>
14
+ <html>
15
+ <head>
16
+ <title>Authentication Success</title>
17
+ <style>
18
+ body {{
19
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Arial, sans-serif;
20
+ display: flex;
21
+ justify-content: center;
22
+ align-items: center;
23
+ height: 100vh;
24
+ margin: 0;
25
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
26
+ }}
27
+ .container {{
28
+ background: white;
29
+ padding: 40px;
30
+ border-radius: 10px;
31
+ box-shadow: 0 10px 40px rgba(0,0,0,0.2);
32
+ text-align: center;
33
+ max-width: 400px;
34
+ }}
35
+ h1 {{
36
+ color: #2ecc71;
37
+ margin: 0 0 20px 0;
38
+ }}
39
+ #countdown {{
40
+ font-size: 24px;
41
+ font-weight: bold;
42
+ color: #667eea;
43
+ }}
44
+ </style>
45
+ </head>
46
+ <body>
47
+ <div class="container">
48
+ <h1>Authentication Successful!</h1>
49
+ <p>Closing in <span id="countdown">{auto_close_delay}</span> seconds...</p>
50
+ <p><small>You can return to JupyterLab now</small></p>
51
+ </div>
52
+
53
+ <script>
54
+ let seconds = {auto_close_delay};
55
+ const countdownElement = document.getElementById('countdown');
56
+
57
+ const interval = setInterval(() => {{
58
+ seconds--;
59
+ countdownElement.textContent = seconds;
60
+
61
+ if (seconds <= 0) {{
62
+ clearInterval(interval);
63
+ window.close();
64
+ setTimeout(() => {{
65
+ window.close();
66
+ }}, 100);
67
+ setTimeout(() => {{
68
+ if (!window.closed) {{
69
+ document.body.innerHTML = '<div class="container"><h2>You can now close this tab</h2><p>Return to JupyterLab to continue</p></div>';
70
+ }}
71
+ }}, 500);
72
+ }}
73
+ }}, 1000);
74
+ </script>
75
+ </body>
76
+ </html>
77
+ """
78
+
79
+
80
+ class ShopifyAuthenticator:
81
+ """
82
+ Authenticate with Shopify using OAuth2.
83
+
84
+ Args:
85
+ shop: Shopify shop name
86
+ key: Shopify API key
87
+ secret: Shopify API secret
88
+ port: Port to use for the local server
89
+ """
90
+
91
+ def __init__(self, shop: str, key: str, secret: str, port: int = 4545) -> None:
92
+ self._shop = shop
93
+ self._key = key or os.getenv("SHOPIFY_API_KEY")
94
+ self._secret = secret or os.getenv("SHOPIFY_API_SECRET")
95
+ self._port = port
96
+
97
+ def authenticate(
98
+ self,
99
+ auto_close_delay: int = DEFAULT_AUTO_CLOSE_DELAY,
100
+ ) -> str | None:
101
+ """
102
+ Authenticate with Shopify using OAuth2.
103
+
104
+ Args:
105
+ auto_close_delay: Delay in seconds to close the browser
106
+
107
+ Returns:
108
+ Access token
109
+ """
110
+ if not self._key or not self._secret or not self._shop:
111
+ raise ValueError("Shopify API key, secret, and shop are required")
112
+
113
+ REDIRECT_URI = f"http://localhost:{self._port}/callback"
114
+
115
+ auth_data = {"code": None}
116
+
117
+ class ShopifyCallbackHandler(BaseHTTPRequestHandler):
118
+ def do_GET(handler_self):
119
+ query = urlparse(handler_self.path).query
120
+ params = parse_qs(query)
121
+
122
+ auth_data["code"] = params.get("code", [None])[0]
123
+
124
+ handler_self.send_response(200)
125
+ handler_self.send_header("Content-type", "text/html")
126
+ handler_self.end_headers()
127
+
128
+ handler_self.wfile.write(
129
+ HTML_AUTH_SUCCESS.format(auto_close_delay=auto_close_delay).encode(
130
+ "utf-8"
131
+ )
132
+ )
133
+
134
+ def log_message(handler_self, format, *args):
135
+ pass
136
+
137
+ auth_params = {
138
+ "client_id": self._key,
139
+ "redirect_uri": REDIRECT_URI,
140
+ "state": "nonce",
141
+ }
142
+
143
+ authorization_url = f"https://{self._shop}.myshopify.com/admin/oauth/authorize?{urlencode(auth_params)}"
144
+
145
+ webbrowser.open(authorization_url)
146
+
147
+ server = HTTPServer(("localhost", self._port), ShopifyCallbackHandler)
148
+ server.handle_request()
149
+
150
+ auth_code = auth_data["code"]
151
+
152
+ # No authorization code received
153
+ if not auth_code:
154
+ logger.error("No authorization code received")
155
+ return None
156
+
157
+ # Exchange authorization code for access token
158
+ token_data = {
159
+ "client_id": self._key,
160
+ "client_secret": self._secret,
161
+ "code": auth_code,
162
+ }
163
+
164
+ token_response = requests.post(
165
+ f"https://{self._shop}.myshopify.com/admin/oauth/access_token",
166
+ json=token_data,
167
+ )
168
+
169
+ if token_response.status_code == 200:
170
+ token_info = token_response.json()
171
+ token = token_info["access_token"]
172
+ return token
173
+ else:
174
+ logger.error(f"Token exchange failed: {token_response.text}")
175
+ return None
shopifyql/client.py ADDED
@@ -0,0 +1,280 @@
1
+ import logging
2
+ import random
3
+ import threading
4
+ import time
5
+ import weakref
6
+ from contextlib import contextmanager
7
+ from typing import TYPE_CHECKING, Any
8
+
9
+ import requests
10
+
11
+ from .limiter import FixedWindowConfig, FixedWindowRateLimiter
12
+ from .results import ShopifyQLRecordsResult, ShopifyQLResult
13
+
14
+ logger = logging.getLogger(__name__)
15
+
16
+ if TYPE_CHECKING:
17
+ import pandas as pd # noqa: F401
18
+ import polars as pl # noqa: F401
19
+
20
+
21
+ class ShopifyQLClient:
22
+ """
23
+ A tiny client for interacting with the Shopify GraphQL API.
24
+
25
+ Args:
26
+ shop: Shopify shop name
27
+ access_token: Shopify access token
28
+ version: Shopify API version
29
+ """
30
+
31
+ DEFAULT_VERSION: str = "2025-10"
32
+ DEFAULT_PORT = 4545
33
+
34
+ @classmethod
35
+ def from_oauth(
36
+ cls,
37
+ shop: str,
38
+ key: str = None,
39
+ secret: str = None,
40
+ version: str = DEFAULT_VERSION,
41
+ port: int = DEFAULT_PORT,
42
+ ) -> "ShopifyQLClient":
43
+ """
44
+ Create a ShopifyQLClient from OAuth authentication.
45
+ Args:
46
+ shop: Shopify shop name
47
+ key: Shopify API key
48
+ secret: Shopify API secret
49
+ version: Shopify API version
50
+ port: Port to use for the local oauth server
51
+ Returns:
52
+ A ShopifyQLClient instance
53
+ """
54
+ from .auth import ShopifyAuthenticator
55
+
56
+ auth = ShopifyAuthenticator(shop=shop, key=key, secret=secret, port=port)
57
+ access_token = auth.authenticate()
58
+ return cls(shop, access_token, version)
59
+
60
+ def __init__(
61
+ self,
62
+ shop: str,
63
+ access_token: str,
64
+ version: str = DEFAULT_VERSION,
65
+ rate_limit_config: FixedWindowConfig | None = None,
66
+ max_retries: int = 3,
67
+ connect_timeout: int = 10,
68
+ pool_maxsize: int = 10,
69
+ ) -> None:
70
+ self._shop = shop
71
+ self._access_token = access_token
72
+ self._api_version = version or self.DEFAULT_VERSION
73
+ self._local = threading.local()
74
+ self._in_context = False
75
+ self._sessions = weakref.WeakSet()
76
+ rate_limit_config = rate_limit_config or FixedWindowConfig()
77
+ self._rate_limiter = FixedWindowRateLimiter(config=rate_limit_config)
78
+ self._max_retries = max_retries
79
+ self._connect_timeout = connect_timeout
80
+ self._pool_maxsize = pool_maxsize
81
+
82
+ # Ensure sessions are closed when the client is garbage collected
83
+ def _finalize_sessions(sessions: weakref.WeakSet):
84
+ for s in list(sessions):
85
+ try:
86
+ s.close()
87
+ except Exception:
88
+ pass
89
+
90
+ self._finalizer = weakref.finalize(self, _finalize_sessions, self._sessions)
91
+
92
+ @contextmanager
93
+ def _get_session(self) -> requests.Session:
94
+ if self._in_context:
95
+ session = getattr(self._local, "session", None)
96
+ if session is None:
97
+ session = requests.Session()
98
+ self._sessions.add(session)
99
+ weakref.finalize(session, session.close)
100
+ self._local.session = session
101
+ yield session
102
+ else:
103
+ with requests.Session() as session:
104
+ yield session
105
+
106
+ def __enter__(self) -> "ShopifyQLClient":
107
+ self._in_context = True
108
+ return self
109
+
110
+ def __exit__(self, exc_type, exc, tb) -> None:
111
+ session = getattr(self._local, "session", None)
112
+ if session is not None:
113
+ try:
114
+ session.close()
115
+ finally:
116
+ self._local.session = None
117
+ self._in_context = False
118
+
119
+ @property
120
+ def url(self):
121
+ """GraphQL endpoint URL"""
122
+ return f"https://{self._shop}.myshopify.com/admin/api/{self._api_version}/graphql.json"
123
+
124
+ def _validate_errors(self, json_response: dict[str, Any]) -> dict[str, Any]:
125
+ """
126
+ Validate the errors in the JSON response and raise a ValueError if there are any.
127
+ Args:
128
+ json_response: The JSON response from the GraphQL API
129
+ Returns:
130
+ The JSON response
131
+ Raises:
132
+ ValueError: If the response contains errors
133
+ """
134
+ if errors := json_response.get("errors"):
135
+ messages = "\n".join([error.get("message") for error in errors])
136
+ raise ValueError(f"ShopifyQLClient errors: \n{messages}")
137
+ return json_response
138
+
139
+ def graphql_query(
140
+ self,
141
+ query: str,
142
+ variables: dict[str, Any] | None = None,
143
+ ) -> dict[str, Any]:
144
+ """
145
+ Execute a GraphQL query and return parsed JSON. Handles rate limit errors and retries.
146
+
147
+ Args:
148
+ query: The GraphQL query to execute
149
+ variables: Variables to pass to the query
150
+
151
+ Returns:
152
+ JSON response from the GraphQL API
153
+
154
+ Raises:
155
+ requests.exceptions.HTTPError: If the response is not 200 OK
156
+ requests.exceptions.RequestException: If the request fails
157
+ ValueError: If the response is not valid JSON
158
+ """
159
+
160
+ headers = {
161
+ "X-Shopify-Access-Token": self._access_token,
162
+ "Content-Type": "application/json",
163
+ }
164
+
165
+ payload: dict[str, Any] = {"query": query}
166
+ if variables is not None:
167
+ payload["variables"] = variables
168
+
169
+ attempt = 0
170
+ while True:
171
+ try:
172
+ # Gate requests using the fixed-window rate limiter
173
+ wait_seconds = self._rate_limiter.acquire()
174
+ if wait_seconds > 0:
175
+ # Add jitter to the wait time to avoid thundering herd
176
+ jitter_ms = random.randint(100, 500)
177
+ time.sleep(wait_seconds + (jitter_ms / 1000.0))
178
+
179
+ # Make the request
180
+ with self._get_session() as session:
181
+ response = session.post(
182
+ self.url,
183
+ headers=headers,
184
+ json=payload,
185
+ timeout=self._connect_timeout,
186
+ )
187
+ response.raise_for_status()
188
+ json_response = response.json()
189
+ return self._validate_errors(json_response)
190
+
191
+ except requests.exceptions.RequestException as e:
192
+ logger.error(f"ShopifyQLClient request exception: {e}")
193
+ if attempt < self._max_retries:
194
+ attempt += 1
195
+ wait_time = (2**attempt) + random.uniform(0, 1)
196
+ time.sleep(wait_time)
197
+ continue
198
+ raise
199
+
200
+ def get_current_scopes(self) -> list[str]:
201
+ """
202
+ Get the current scopes granted to the app.
203
+ Returns:
204
+ List of scopes granted to the app
205
+ """
206
+
207
+ gql = """
208
+ query AccessScopeList {
209
+ currentAppInstallation {
210
+ accessScopes {
211
+ handle
212
+ }
213
+ }
214
+ }
215
+ """
216
+ json_response = self.graphql_query(gql)
217
+ return [
218
+ scope.get("handle")
219
+ for scope in json_response.get("data", {})
220
+ .get("currentAppInstallation", {})
221
+ .get("accessScopes", [])
222
+ ]
223
+
224
+ def query(
225
+ self,
226
+ shopifyql_query: str,
227
+ result_class: type[ShopifyQLResult] | None = None,
228
+ ) -> Any:
229
+ """
230
+ Execute a ShopifyQL query and return a result object.
231
+
232
+ Args:
233
+ shopifyql_query: The ShopifyQL query to execute
234
+ result_class: The class to use to parse the result
235
+
236
+ Returns:
237
+ Result object
238
+
239
+ Raises:
240
+ ValueError: If the response does not contain valid table data
241
+ """
242
+ gql = """
243
+ query ($q: String!) {
244
+ shopifyqlQuery(query: $q) {
245
+ tableData { columns { name dataType displayName } rows }
246
+ parseErrors
247
+ }
248
+ }
249
+ """
250
+ json_response = self.graphql_query(gql, variables={"q": shopifyql_query})
251
+ if not json_response:
252
+ current_scopes = self.get_current_scopes()
253
+ raise ValueError(
254
+ f"Empty response from ShopifyQL API, make sure you have the correct scopes enabled in your Shopify app settings. Check our docs: https://shopify.dev/docs/api/admin-graphql/latest/queries/shopifyqlQuery \n Current Scopes: {current_scopes}"
255
+ )
256
+
257
+ table_data = (
258
+ json_response.get("data", {}).get("shopifyqlQuery", {}).get("tableData", {})
259
+ )
260
+ if not table_data or not table_data.get("columns"):
261
+ logger.warning(f"Current Scopes: {self.get_current_scopes()}")
262
+ raise ValueError(
263
+ "Server returned no valid table data, make sure you have requested the correct scopes. Check our docs: https://shopify.dev/docs/api/admin-graphql/latest/queries/shopifyqlQuery \n Current Scopes: {current_scopes}"
264
+ )
265
+
266
+ rc: type[ShopifyQLResult] = result_class or ShopifyQLRecordsResult
267
+ return rc.from_table_data(table_data)
268
+
269
+ def query_records(self, shopifyql_query: str) -> list[dict[str, Any]]:
270
+ return self.query(shopifyql_query, result_class=ShopifyQLRecordsResult)
271
+
272
+ def query_pandas(self, shopifyql_query: str) -> "pd.DataFrame":
273
+ from .results import ShopifyQLPandasResult
274
+
275
+ return self.query(shopifyql_query, result_class=ShopifyQLPandasResult)
276
+
277
+ def query_polars(self, shopifyql_query: str) -> "pl.DataFrame":
278
+ from .results import ShopifyQLPolarsResult
279
+
280
+ return self.query(shopifyql_query, result_class=ShopifyQLPolarsResult)
shopifyql/limiter.py ADDED
@@ -0,0 +1,44 @@
1
+ import threading
2
+ import time
3
+ from dataclasses import dataclass
4
+
5
+
6
+ @dataclass(frozen=True)
7
+ class FixedWindowConfig:
8
+ window_seconds: int = 60
9
+ max_requests: int = 1000
10
+
11
+
12
+ class FixedWindowRateLimiter:
13
+ """Thread-safe fixed-window limiter.
14
+
15
+ Aligns windows to epoch boundaries: floor(now / window_seconds) * window_seconds.
16
+ """
17
+
18
+ def __init__(self, *, config: FixedWindowConfig) -> None:
19
+ self._config = config
20
+ self._lock = threading.Lock()
21
+ self._window_start = self._current_window_start()
22
+ self._count = 0
23
+
24
+ def _current_window_start(self) -> int:
25
+ now = int(time.time())
26
+ return (now // self._config.window_seconds) * self._config.window_seconds
27
+
28
+ def acquire(self) -> float:
29
+ """Attempt to take a permit. Returns 0 if allowed, else seconds to wait until next window."""
30
+ with self._lock:
31
+ now_window = self._current_window_start()
32
+ if now_window != self._window_start:
33
+ self._window_start = now_window
34
+ self._count = 0
35
+
36
+ if self._count < self._config.max_requests:
37
+ self._count += 1
38
+ return 0.0
39
+
40
+ # Compute time remaining to next window
41
+ now = int(time.time())
42
+ next_window = self._window_start + self._config.window_seconds
43
+ wait = max(0, next_window - now)
44
+ return float(wait)
shopifyql/results.py ADDED
@@ -0,0 +1,170 @@
1
+ from abc import ABC, abstractmethod
2
+ from collections.abc import Iterable, Mapping
3
+ from typing import Any
4
+
5
+
6
+ class ShopifyQLResult(ABC):
7
+ """
8
+ Abstract base class for ShopifyQL result objects.
9
+
10
+ Args:
11
+ table_data: The table data from the ShopifyQL API
12
+
13
+ Returns:
14
+ The result object. Subclasses must implement this method.
15
+ """
16
+
17
+ @classmethod
18
+ @abstractmethod
19
+ def from_table_data(cls, table_data: dict[str, Any]) -> Any: ...
20
+
21
+
22
+ class ShopifyQLRecordsResult(ShopifyQLResult):
23
+ """
24
+ Dependency-free result that returns a list of dictionaries (records).
25
+ Keys are column names and values are row values.
26
+ """
27
+
28
+ @classmethod
29
+ def from_table_data(cls, table_data: dict[str, Any]) -> list[dict[str, Any]]:
30
+ columns = table_data.get("columns", [])
31
+ rows = table_data.get("rows", [])
32
+ column_names = [c.get("name") for c in columns]
33
+ return [dict(zip(column_names, row)) for row in rows]
34
+
35
+
36
+ class ShopifyQLPandasResult(ShopifyQLResult):
37
+ """
38
+ Result object for ShopifyQL queries that returns a pandas DataFrame.
39
+ """
40
+
41
+ TYPES_MAP: dict[str, object] = {
42
+ "UNSPECIFIED": "string",
43
+ "MONEY": "Float64",
44
+ "PERCENT": "Float64",
45
+ "INTEGER": "Int64",
46
+ "FLOAT": "Float64",
47
+ "DECIMAL": "Float64",
48
+ "STRING": "string",
49
+ "BOOLEAN": "boolean",
50
+ "TIMESTAMP": "datetime64[ns]",
51
+ "SECOND_TIMESTAMP": "datetime64[ns]",
52
+ "MINUTE_TIMESTAMP": "datetime64[ns]",
53
+ "HOUR_TIMESTAMP": "datetime64[ns]",
54
+ "DAY_TIMESTAMP": "datetime64[ns]",
55
+ "WEEK_TIMESTAMP": "datetime64[ns]",
56
+ "MONTH_TIMESTAMP": "datetime64[ns]",
57
+ "QUARTER_TIMESTAMP": "datetime64[ns]",
58
+ "YEAR_TIMESTAMP": "datetime64[ns]",
59
+ "DAY_OF_WEEK": "Int64",
60
+ "HOUR_OF_DAY": "Int64",
61
+ "MONTH_OF_YEAR": "Int64",
62
+ "WEEK_OF_YEAR": "Int64",
63
+ "IDENTITY": "string",
64
+ "ARRAY": "object",
65
+ "MILLISECOND_DURATION": "timedelta64[ns]",
66
+ "SECOND_DURATION": "timedelta64[ns]",
67
+ "MINUTE_DURATION": "timedelta64[ns]",
68
+ "HOUR_DURATION": "timedelta64[ns]",
69
+ "DAY_DURATION": "timedelta64[ns]",
70
+ "CUMULATIVE": "Float64",
71
+ }
72
+
73
+ @classmethod
74
+ def _pandas_dtypes_from_columns(
75
+ cls, columns: Iterable[Mapping[str, Any]]
76
+ ) -> dict[str, object]:
77
+ pandas_dtypes: dict[str, object] = {}
78
+ for column in columns:
79
+ column_name = str(column.get("name", ""))
80
+ shopifyql_type = str(column.get("dataType", "")).upper()
81
+ pandas_dtype = cls.TYPES_MAP.get(shopifyql_type, "string")
82
+ if column_name:
83
+ pandas_dtypes[column_name] = pandas_dtype
84
+ return pandas_dtypes
85
+
86
+ @classmethod
87
+ def from_table_data(cls, table_data: dict[str, Any]) -> Any:
88
+ try:
89
+ import pandas as pd # type: ignore
90
+ except ImportError as e:
91
+ raise ImportError(
92
+ "pandas is not installed. Install with 'pip install shopifyql[pandas]' or 'pip install pandas'."
93
+ ) from e
94
+
95
+ data_types = cls._pandas_dtypes_from_columns(table_data["columns"])
96
+ column_names = [str(c.get("name", "")) for c in table_data["columns"]]
97
+ df = pd.DataFrame(table_data["rows"], columns=column_names)
98
+ return df.astype(data_types)
99
+
100
+
101
+ class ShopifyQLPolarsResult(ShopifyQLResult):
102
+ """
103
+ Result object for ShopifyQL queries that returns a polars DataFrame.
104
+ """
105
+
106
+ @classmethod
107
+ def _polars_dtypes_from_columns(
108
+ cls, columns: Iterable[Mapping[str, Any]]
109
+ ) -> dict[str, object]:
110
+ # Build a Polars-specific mapping to concrete pl.DataType objects
111
+ try:
112
+ import polars as pl # type: ignore
113
+ except ImportError:
114
+ # Defer error handling to caller
115
+ raise
116
+
117
+ dtype_map: dict[str, object] = {
118
+ "UNSPECIFIED": pl.String,
119
+ "MONEY": pl.Float64,
120
+ "PERCENT": pl.Float64,
121
+ "INTEGER": pl.Int64,
122
+ "FLOAT": pl.Float64,
123
+ "DECIMAL": pl.Float64,
124
+ "STRING": pl.String,
125
+ "BOOLEAN": pl.Boolean,
126
+ "TIMESTAMP": pl.Datetime(time_unit="ns"),
127
+ "SECOND_TIMESTAMP": pl.Datetime(time_unit="ns"),
128
+ "MINUTE_TIMESTAMP": pl.Datetime(time_unit="ns"),
129
+ "HOUR_TIMESTAMP": pl.Datetime(time_unit="ns"),
130
+ "DAY_TIMESTAMP": pl.Datetime(time_unit="ns"),
131
+ "WEEK_TIMESTAMP": pl.Datetime(time_unit="ns"),
132
+ "MONTH_TIMESTAMP": pl.Datetime(time_unit="ns"),
133
+ "QUARTER_TIMESTAMP": pl.Datetime(time_unit="ns"),
134
+ "YEAR_TIMESTAMP": pl.Datetime(time_unit="ns"),
135
+ "DAY_OF_WEEK": pl.Int64,
136
+ "HOUR_OF_DAY": pl.Int64,
137
+ "MONTH_OF_YEAR": pl.Int64,
138
+ "WEEK_OF_YEAR": pl.Int64,
139
+ "IDENTITY": pl.String,
140
+ # ARRAY intentionally omitted to allow inference for heterogeneous data
141
+ "MILLISECOND_DURATION": pl.Duration(time_unit="ns"),
142
+ "SECOND_DURATION": pl.Duration(time_unit="ns"),
143
+ "MINUTE_DURATION": pl.Duration(time_unit="ns"),
144
+ "HOUR_DURATION": pl.Duration(time_unit="ns"),
145
+ "DAY_DURATION": pl.Duration(time_unit="ns"),
146
+ "CUMULATIVE": pl.Float64,
147
+ }
148
+
149
+ polars_dtypes: dict[str, object] = {}
150
+ for column in columns:
151
+ column_name = str(column.get("name", ""))
152
+ shopifyql_type = str(column.get("dataType", "")).upper()
153
+ polars_dtype = dtype_map.get(shopifyql_type)
154
+ if column_name and polars_dtype is not None:
155
+ polars_dtypes[column_name] = polars_dtype
156
+ return polars_dtypes
157
+
158
+ @classmethod
159
+ def from_table_data(cls, table_data: dict[str, Any]) -> Any:
160
+ try:
161
+ import polars as pl # type: ignore
162
+ except ImportError as e:
163
+ raise ImportError(
164
+ "polars is not installed. Install with 'pip install shopifyql[polars]' or 'pip install polars'."
165
+ ) from e
166
+
167
+ column_names = [str(c.get("name", "")) for c in table_data["columns"]]
168
+ data_types = cls._polars_dtypes_from_columns(table_data["columns"])
169
+ df = pl.DataFrame(table_data["rows"], schema=column_names, orient="row")
170
+ return df.cast(data_types)
@@ -0,0 +1,232 @@
1
+ Metadata-Version: 2.4
2
+ Name: shopifyql
3
+ Version: 0.1.2
4
+ Summary: Python SDK and utilities for ShopifyQL queries
5
+ Author-email: "Shopify Inc." <opensource@shopify.com>
6
+ License: Copyright 2025-present, Shopify Inc.
7
+
8
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
11
+
12
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
13
+ License-File: LICENSE.md
14
+ Keywords: Shopify,ShopifyQL,analytics,ecommerce
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python
18
+ Classifier: Programming Language :: Python :: 3
19
+ Classifier: Programming Language :: Python :: 3 :: Only
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Programming Language :: Python :: 3.13
23
+ Classifier: Topic :: Software Development :: Libraries
24
+ Requires-Python: <4,>=3.11
25
+ Requires-Dist: requests>=2.32
26
+ Provides-Extra: all
27
+ Requires-Dist: pandas>=2.2; extra == 'all'
28
+ Requires-Dist: polars>=1.0; extra == 'all'
29
+ Provides-Extra: pandas
30
+ Requires-Dist: pandas>=2.2; extra == 'pandas'
31
+ Provides-Extra: polars
32
+ Requires-Dist: polars>=1.0; extra == 'polars'
33
+ Description-Content-Type: text/markdown
34
+
35
+ # shopifyql
36
+
37
+ Python SDK for running ShopifyQL queries from Python. It aims to make it fast and easy to get your store data with minimal setup, while staying flexible for power users.
38
+
39
+ Key points:
40
+
41
+ - No hard runtime deps by default (only `requests`).
42
+ - Choose your result backend: dependency-free records (default), pandas, or polars.
43
+ - Optional OAuth helper to obtain an access token during development.
44
+
45
+ ## Quick setup with CLI template
46
+
47
+ For the easiest way to test this package, you can use our CLI template that sets up everything for you to start working in a Jupyter Notebook with access to your store:
48
+
49
+ ```bash
50
+ shopify app init --template=https://github.com/Shopify/shopify-app-notebooks-template
51
+ ```
52
+
53
+ This template will:
54
+ - Set up a Python 3.11+ environment with all dependencies needed to run `shopifyql` inside Jupyter notebooks
55
+ - Handle app configuration and authentication automatically
56
+ - Provide a ready-to-use development environment powered by Shopify CLI
57
+
58
+ See the [template repository](https://github.com/Shopify/shopify-app-notebooks-template) for more details.
59
+
60
+ ## Requirements
61
+
62
+ - Python 3.11+
63
+ - A Shopify `shop` (e.g., `your-shop-name`) and an Admin API access token with access to the `read_reports` scope.
64
+
65
+ ## Installation
66
+
67
+ Base (no heavy dependencies):
68
+
69
+ ```bash
70
+ pip install shopifyql
71
+ ```
72
+
73
+ With pandas support:
74
+
75
+ ```bash
76
+ pip install "shopifyql[pandas]"
77
+ ```
78
+
79
+ With polars support:
80
+
81
+ ```bash
82
+ pip install "shopifyql[polars]"
83
+ ```
84
+
85
+ With both pandas and polars:
86
+
87
+ ```bash
88
+ pip install "shopifyql[all]"
89
+ ```
90
+
91
+ Using uv for local development of this repo:
92
+
93
+ ```bash
94
+ uv venv
95
+ uv sync --group dev
96
+ ```
97
+
98
+ ## Quick start
99
+
100
+ The default return type is a list of dict records, so you can use the library without dependencies if needed.
101
+
102
+ ```python
103
+ from shopifyql import ShopifyQLClient
104
+
105
+ client = ShopifyQLClient(shop="your-shop", access_token="shpat_...")
106
+
107
+ records = client.query("FROM sales SHOW total_sales SINCE 2025-01-01 UNTIL 2025-12-31")
108
+ print(records[:2]) # e.g., [{"total_sales": 123.45}, {"total_sales": 67.89}]
109
+ ```
110
+
111
+ ### Using pandas
112
+
113
+ ```bash
114
+ pip install "shopifyql[pandas]"
115
+ ```
116
+
117
+ ```python
118
+ from shopifyql import ShopifyQLClient, ShopifyQLPandasResult
119
+
120
+ client = ShopifyQLClient(shop="your-shop", access_token="shpat_...")
121
+ df = client.query_pandas("FROM sales SHOW orders TIMESERIES DAY SINCE -30d")
122
+ print(df.head())
123
+ ```
124
+
125
+ ### Using polars
126
+
127
+ ```bash
128
+ pip install "shopifyql[polars]"
129
+ ```
130
+
131
+ ```python
132
+ from shopifyql import ShopifyQLClient, ShopifyQLPolarsResult
133
+
134
+ client = ShopifyQLClient(shop="your-shop", access_token="shpat_...")
135
+ df = client.query_polars("FROM sales SHOW total_sales group by product_title")
136
+ print(df.head())
137
+ ```
138
+
139
+ ## OAuth helper (optional)
140
+
141
+ If you don’t have a token handy, you can use a local browser OAuth helper to obtain one during development:
142
+
143
+ ```python
144
+ from shopifyql import ShopifyQLClient
145
+
146
+ client = ShopifyQLClient.from_oauth(
147
+ shop="your-shop",
148
+ key="your_api_key",
149
+ secret="your_api_secret",
150
+ port = 4545
151
+ )
152
+
153
+ df = client.query_pandas("FROM sales SHOW total_sales SINCE -7d")
154
+ ```
155
+
156
+ ### Steps for oauth
157
+ - Requires read_reports access scope. Also: Level 2 access to Customer data including name, address, phone, and email fields. Please refer to https://shopify.dev/docs/apps/launch/protected-customer-data. Scopes caan be modified in your app version settings: https://dev.shopify.com/dashboard/ -> Your App -> Versions -> Create a version
158
+ - A valid redirect_uri is needed for this oauth flow to work, please use `http://localhost:4545/callback`
159
+ - You can only receive scopes that are enabled in your app settings, if you need more you will want to submit a new app version.
160
+ - If your browser lands on `admin.shopify.com/.../oauth/authorize` and the helper never returns to `http://localhost:4545/callback`, your app’s Redirect URLs probably don’t include the exact `redirect_uri`. Add `http://localhost:4545/callback` (or the port you pass, configurable in from_oauth) to App setup → Redirect URLs, then try again. The `redirect_uri` must match exactly.
161
+ - After auth, you can confirm what the scopes are currently available with:
162
+
163
+ ```python
164
+ scopes = client.get_current_scopes()
165
+ print(scopes)
166
+ ```
167
+
168
+ ## Context manager and connection reuse
169
+
170
+ When running multiple queries, use the client as a context manager to reuse a keep-alive `requests.Session` per thread and avoid repeated TLS/HTTP setup costs:
171
+
172
+ ```python
173
+ from shopifyql import ShopifyQLClient
174
+
175
+ SHOP = "your-shop"
176
+ ACCESS_TOKEN = "shpat_..."
177
+
178
+ with ShopifyQLClient(SHOP, ACCESS_TOKEN) as client:
179
+ df1 = client.query_pandas("FROM sales SHOW total_sales GROUP BY product_title SINCE -30d UNTIL now")
180
+ df2 = client.query_pandas("FROM sales SHOW net_sales GROUP BY product_title SINCE -30d UNTIL now")
181
+ print(df1.merge(df2, on="product_title"))
182
+ ```
183
+
184
+ ## Custom result classes
185
+
186
+ You can provide your own result transformer by implementing `ShopifyQLResult`:
187
+
188
+ ```python
189
+ from typing import Any
190
+ from shopifyql import ShopifyQLClient, ShopifyQLResult
191
+
192
+ class MyResult(ShopifyQLResult):
193
+ @classmethod
194
+ def from_table_data(cls, table_data: dict[str, Any]) -> Any:
195
+ # Transform the ShopifyQL tableData into your preferred structure
196
+ return {c["name"]: [row[i] for i, _ in enumerate(table_data["columns"])] for i, c in enumerate(table_data["columns"])}
197
+
198
+ client = ShopifyQLClient(shop="your-shop", access_token="shpat_...")
199
+ custom = client.query("from sales show total_sales", result_class=MyResult)
200
+ ```
201
+
202
+ ## Error handling & rate limits
203
+
204
+ The client will:
205
+
206
+ - Gate requests with a fixed-window rate limiter to avoid 429s; if the window is exhausted, it sleeps until the next window (with jitter).
207
+ - Backoff and retry on transient request errors (and other request exceptions) up to `max_retries`.
208
+
209
+ You may see:
210
+
211
+ - `requests.exceptions.HTTPError` for non-2xx HTTP responses (after retries as applicable).
212
+ - `requests.exceptions.RequestException` for network errors (after retries).
213
+ - `ValueError("No valid table data found in response")` when the ShopifyQL response is malformed.
214
+
215
+ ## Configuration
216
+
217
+ - API version: defaults to `2025-10`. Override via constructor `version="YYYY-MM"`.
218
+ - Timeout: defaults to 10s per request via constructor `connect_timeout`.
219
+ - Retries: defaults to `max_retries=3` with exponential backoff and jitter.
220
+ - Rate limiting: `FixedWindowConfig(window_seconds=60, max_requests=1000)` by default; override via `rate_limit_config`.
221
+ - Connections: when used as a context manager, the client reuses a per-thread `requests.Session` (keep-alive); outside a context it uses ephemeral sessions.
222
+ - Connection pool: `pool_maxsize=10` by default.
223
+
224
+ ## Development
225
+
226
+ Clone and develop with uv or pip:
227
+
228
+ ```bash
229
+ uv venv
230
+ uv sync --group=dev
231
+ pytest -q
232
+ ```
@@ -0,0 +1,9 @@
1
+ shopifyql/__init__.py,sha256=_ddERlnJp5laJLT6CnpfOyquhouzQdBeh_beSCG11FY,498
2
+ shopifyql/auth.py,sha256=JI9NiUBBI2TXp1jC_9FV0Y2kDmZPJfvHA8n3L4V1Ie0,5453
3
+ shopifyql/client.py,sha256=mPQscOXoW45S6M9sNuOzU5qULWS-lPKTDvr2O12l86E,9602
4
+ shopifyql/limiter.py,sha256=RVhfgKQcQKrJreFfIdzw-kg-i27SCP032rWPdPn4lbU,1410
5
+ shopifyql/results.py,sha256=F2v5McQETyNQ27nZxs1aU5IuXhryQvgsKjdN6oTyK7E,6328
6
+ shopifyql-0.1.2.dist-info/METADATA,sha256=lqAbw0mjwq2l97wnGELHdYMW_ogirVol5XLL4mnpCbo,8813
7
+ shopifyql-0.1.2.dist-info/WHEEL,sha256=WLgqFyCfm_KASv4WHyYy0P3pM_m7J5L9k2skdKLirC8,87
8
+ shopifyql-0.1.2.dist-info/licenses/LICENSE.md,sha256=m_aJq6dKe1NkQ21_88KDiwxj59UC1HChWZhBwPQfAHk,1061
9
+ shopifyql-0.1.2.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.28.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,7 @@
1
+ Copyright 2025-present, Shopify Inc.
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4
+
5
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6
+
7
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.