-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathplex_api.py
More file actions
360 lines (303 loc) · 12.8 KB
/
plex_api.py
File metadata and controls
360 lines (303 loc) · 12.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
"""
Plex Connect REST API Client
Grace Engineering — CNC Tool Management
========================================
Base URL: https://connect.plex.com/{collection}/{version}/{resource}
Auth: X-Plex-Connect-Api-Key header (Consumer Key from Developer Portal)
Rate: 200 calls/minute
"""
import requests
import json
import csv
import time
import os
from datetime import datetime
# ─────────────────────────────────────────────
# CONFIGURATION — fill these in
# ─────────────────────────────────────────────
API_KEY = "k3SmLW3y3mhqJiG6osixbYUmiPsHfB51" # from developers.plex.com → My Apps
TENANT_ID = "a6af9c99-bce5-4938-a007-364dc5603d08" # leave blank for default tenant (your PCN)
BASE_URL = "https://connect.plex.com"
TEST_URL = "https://test.connect.plex.com"
USE_TEST = False # flip to True to hit test environment first
OUTPUT_DIR = "C:/projects/plex-api/outputs"
TOOL_LIB_DIR = "Z:\\Engineering\\Tooling\\Fusion_Libraries" # Mapped drive path containing JSON files
# ─────────────────────────────────────────────
# BASE CLIENT
# ─────────────────────────────────────────────
class PlexClient:
def __init__(self, api_key, tenant_id="", use_test=False):
self.base = TEST_URL if use_test else BASE_URL
self.headers = {
"X-Plex-Connect-Api-Key": api_key,
"Content-Type": "application/json",
"Accept": "application/json",
}
if tenant_id:
self.headers["X-Plex-Connect-Tenant-Id"] = tenant_id
self._call_count = 0
self._window_start = time.time()
def _throttle(self):
"""Stay under 200 calls/minute rate limit"""
self._call_count += 1
elapsed = time.time() - self._window_start
if elapsed < 60 and self._call_count >= 190:
wait = 60 - elapsed
print(f" Rate limit approaching — waiting {wait:.1f}s...")
time.sleep(wait)
self._call_count = 0
self._window_start = time.time()
elif elapsed >= 60:
self._call_count = 1
self._window_start = time.time()
def get(self, collection, version, resource, params=None):
"""GET request with auto-throttling and error handling"""
self._throttle()
url = f"{self.base}/{collection}/{version}/{resource}"
try:
r = requests.get(url, headers=self.headers, params=params, timeout=30)
r.raise_for_status()
return r.json()
except requests.exceptions.HTTPError as e:
print(f" HTTP Error {r.status_code}: {url}")
print(f" Response: {r.text[:300]}")
return None
except Exception as e:
print(f" Error: {e}")
return None
def get_paginated(self, collection, version, resource, params=None, limit=100):
"""GET all pages of a paginated endpoint"""
params = params or {}
params["limit"] = limit
params["offset"] = 0
results = []
while True:
data = self.get(collection, version, resource, params)
if not data:
break
# Handle both list and dict responses
if isinstance(data, list):
batch = data
elif isinstance(data, dict):
# Common Plex patterns: data["items"], data["rows"], or data itself
batch = (data.get("items") or
data.get("rows") or
data.get("data") or
[data])
else:
break
if not batch:
break
results.extend(batch)
print(f" Fetched {len(results)} records...")
if len(batch) < limit:
break # last page
params["offset"] += limit
return results
# ─────────────────────────────────────────────
# ENDPOINT EXPLORER
# Helps discover what endpoints are available
# and what fields they return
# ─────────────────────────────────────────────
def explore_endpoint(client, collection, version, resource, params=None, max_records=3):
"""
Fetch a small sample from an endpoint and pretty-print the structure.
Use this to understand field names before writing extraction code.
"""
print(f"\n{'='*60}")
print(f"Exploring: {collection}/{version}/{resource}")
print(f"{'='*60}")
params = params or {}
params["limit"] = max_records
data = client.get(collection, version, resource, params)
if data is None:
print(" No response / endpoint may not exist or not be subscribed")
return None
print(f" Response type: {type(data).__name__}")
print(f" Content:\n{json.dumps(data, indent=2)[:2000]}")
return data
# ─────────────────────────────────────────────
# EXTRACTION FUNCTIONS
# ─────────────────────────────────────────────
def extract_purchase_orders(client, supplier=None, date_from=None):
"""
Pull PO data — primary source for tool numbers already in system.
Goal: find all tool-related POs to seed Tool Assembly records.
"""
print("\nExtracting Purchase Orders...")
params = {}
if supplier:
params["supplier"] = supplier
if date_from:
params["updatedAfter"] = f"{date_from}T00:00:00.000Z"
# Try common Plex PO endpoint patterns
# Actual endpoint confirmed from developer portal subscription
results = client.get_paginated("purchasing", "v1", "purchase-orders", params)
if results:
out = os.path.join(OUTPUT_DIR, "plex_purchase_orders.csv")
write_csv(results, out)
print(f" Saved {len(results)} POs → {out}")
return results
def extract_parts(client, part_type=None):
"""
Pull part master records.
Goal: confirm part numbers for Tool BOM linkage.
"""
print("\nExtracting Parts...")
params = {}
if part_type:
params["type"] = part_type
results = client.get_paginated("mdm", "v1", "parts", params)
if results:
out = os.path.join(OUTPUT_DIR, "plex_parts.csv")
write_csv(results, out)
print(f" Saved {len(results)} parts → {out}")
return results
def extract_workcenters(client):
"""
Pull workcenter records.
Goal: confirm workcenter codes for Tool BOM Station assignments.
"""
print("\nExtracting Workcenters...")
results = client.get_paginated("production", "v1/control", "workcenters")
if results:
out = os.path.join(OUTPUT_DIR, "plex_workcenters.csv")
write_csv(results, out)
print(f" Saved {len(results)} workcenters → {out}")
return results
def extract_operations(client):
"""
Pull operation codes.
Goal: confirm operation codes for Tool BOM and routing linkage.
"""
print("\nExtracting Operations...")
results = client.get_paginated("manufacturing", "v1", "operations")
if results:
out = os.path.join(OUTPUT_DIR, "plex_operations.csv")
write_csv(results, out)
print(f" Saved {len(results)} operations → {out}")
return results
# ─────────────────────────────────────────────
# UTILITY
# ─────────────────────────────────────────────
def write_csv(records, filepath):
"""Write list of dicts to CSV, auto-detecting headers"""
if not records:
print(" Nothing to write")
return
os.makedirs(os.path.dirname(filepath), exist_ok=True)
headers = list(records[0].keys()) if records else []
with open(filepath, "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=headers, extrasaction="ignore")
writer.writeheader()
writer.writerows(records)
# ─────────────────────────────────────────────
# ENDPOINT DISCOVERY
# Run this first to see what's available
# ─────────────────────────────────────────────
ENDPOINTS_TO_PROBE = [
# collection version resource
("purchasing", "v1", "purchase-orders"),
("purchasing", "v1", "purchase-order-lines"),
("mdm", "v1", "parts"),
("production", "v1/control", "workcenters"),
("manufacturing", "v1", "operations"),
("manufacturing", "v1", "routings"),
("inventory", "v1", "inventory"),
("tooling", "v1", "tools"),
("tooling", "v1", "tool-assemblies"),
("tooling", "v1", "tool-inventory"),
]
def discover_all(client):
"""
Probe all known endpoint patterns.
Shows which ones your API subscription covers.
Saves a discovery report.
"""
print("\nDiscovering available endpoints...")
report = []
for collection, version, resource in ENDPOINTS_TO_PROBE:
url = f"{client.base}/{collection}/{version}/{resource}"
client._throttle()
try:
r = requests.get(
url,
headers=client.headers,
params={"limit": 1},
timeout=15
)
status = r.status_code
note = ""
if status == 200:
note = "✅ Available"
elif status == 401:
note = "❌ Auth error"
elif status == 403:
note = "🔒 Not subscribed"
elif status == 404:
note = "❓ Not found"
else:
note = f"⚠️ HTTP {status}"
except Exception as e:
status = 0
note = f"❌ Exception: {e}"
print(f" {note:25s} {collection}/{version}/{resource}")
report.append({
"Collection": collection,
"Version": version,
"Resource": resource,
"Status": status,
"Note": note.strip(),
})
time.sleep(0.3) # be polite
out = os.path.join(OUTPUT_DIR, "plex_api_discovery.csv")
write_csv(report, out)
print(f"\nDiscovery report saved → {out}")
return report
# ─────────────────────────────────────────────
# MAIN — edit what you want to run
# ─────────────────────────────────────────────
def explore_parts(client):
"""
Hit the Parts endpoint raw — no params — and dump everything.
"""
print(f"\n{'='*60}")
print("PARTS ENDPOINT — RAW RESPONSE")
print(f"{'='*60}")
url = f"{client.base}/mdm/v1/parts"
print(f"\n GET {url}")
r = requests.get(url, headers=client.headers, timeout=30)
print(f" Status: {r.status_code}")
print(f" Content-Type: {r.headers.get('Content-Type')}")
if r.status_code != 200:
print(f" Body: {r.text[:500]}")
return
data = r.json()
# Dump full raw response
raw = json.dumps(data, indent=2)
print(f" Response length: {len(raw)} chars")
print(f"\n{raw[:5000]}")
if len(raw) > 5000:
print(f"\n ... truncated ({len(raw)} total chars) ...")
# Save full response to file for inspection
out = os.path.join(OUTPUT_DIR, "plex_parts_raw.json")
os.makedirs(os.path.dirname(out), exist_ok=True)
with open(out, "w", encoding="utf-8") as f:
json.dump(data, f, indent=2)
print(f"\n Full response saved → {out}")
return data
if __name__ == "__main__":
client = PlexClient(
api_key=API_KEY,
tenant_id=TENANT_ID,
use_test=USE_TEST,
)
print(f"Plex API Client — {'TEST' if USE_TEST else 'PRODUCTION'}")
print(f"Base URL: {client.base}")
print(f"Key: {API_KEY[:8]}{'*' * 20}")
# ── Focus: Parts endpoint exploration
explore_parts(client)
# ── Other exploration (uncomment as needed)
# discover_all(client)
# extract_parts(client)
# explore_endpoint(client, "mdm", "v1", "parts", max_records=2)