Last active
October 21, 2024 16:47
-
-
Save BFTrick/cca3ec2839f77c31b961acd46592d099 to your computer and use it in GitHub Desktop.
Use the Ship Hero GraphQL API to get all orders & tracking numbers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
from gql import gql, Client | |
from gql.transport.requests import RequestsHTTPTransport | |
from gql.transport.exceptions import TransportQueryError | |
import json | |
import time | |
import os | |
bearer = "YOURBEARERTOKEN" | |
query_template_orders = """query($cursor: String, $startDate: ISODateTime!, $endDate: ISODateTime!, $shopName: String!) { | |
orders(order_date_from: $startDate, order_date_to: $endDate, shop_name: $shopName) { | |
request_id | |
complexity | |
data(first: 500, after: $cursor) { | |
pageInfo { | |
endCursor | |
hasNextPage | |
} | |
edges { | |
node { | |
id | |
order_number | |
fulfillment_status | |
shop_name | |
order_date | |
} | |
} | |
} | |
} | |
}""" | |
query_template_shipments = """query($order_id: String!) { | |
shipments(order_id: $order_id) { | |
data { | |
edges { | |
node { | |
shipping_labels { | |
tracking_number | |
} | |
} | |
} | |
} | |
} | |
}""" | |
_transport = RequestsHTTPTransport( | |
url='https://public-api.shiphero.com/graphql', | |
use_json=True, | |
) | |
_transport.headers = { | |
"User-Agent": "Mozilla/5.0 (X11; buntu; Linux x86_64; rv:58.0) Gecko/0100101 Firefox/58.0", | |
"Authorization": "Bearer {}".format(bearer), | |
"content-type": "application/json", | |
} | |
client = Client(transport=_transport, fetch_schema_from_transport=True) | |
query_orders = gql(query_template_orders) | |
query_shipments = gql(query_template_shipments) | |
def get_tracking_number(order_id): | |
try: | |
variables = {"order_id": order_id} | |
print(f"Querying shipments for order_id: {order_id}") | |
result = client.execute(query_shipments, variable_values=variables) | |
# Print the entire response from the API | |
#print("API Response:") | |
#print(json.dumps(result, indent=2)) | |
shipments = result['shipments']['data']['edges'] | |
if shipments: | |
shipping_labels = shipments[0]['node']['shipping_labels'] | |
if shipping_labels: | |
return shipping_labels[0]['tracking_number'] | |
else: | |
print(f"No shipments found for order_id: {order_id}") | |
return None | |
except TransportQueryError as e: | |
error_data = e.errors[0] | |
print(f"Error occurred: {error_data}") | |
if error_data['code'] == 30: | |
print(f"Rate limit hit. Waiting for 120 seconds.") | |
time.sleep(120) | |
return get_tracking_number(order_id) | |
else: | |
raise e | |
except Exception as e: | |
print(f"An unexpected error occurred: {e}") | |
return None | |
batch_number = 1 | |
cursor = None | |
start_date = "2024-10-01T00:00:00Z" | |
end_date = "2024-10-01T23:59:59Z" | |
shop_name = "Xero Shoes Live" # Specific shop name | |
total_orders = 0 | |
all_orders = [] | |
while True: | |
try: | |
print(f"Executing query for batch {batch_number}") | |
variables = {"cursor": cursor, "startDate": start_date, "endDate": end_date, "shopName": shop_name} | |
result = client.execute(query_orders, variable_values=variables) | |
for order in result['orders']['data']['edges']: | |
order_data = order['node'] | |
tracking_number = get_tracking_number(order_data['id']) | |
order_data['tracking_number'] = tracking_number | |
all_orders.append(order_data) | |
total_orders += 1 | |
print(f"Total number of orders so far: {total_orders}") | |
batch_number += 1 | |
# Update cursor for the next batch | |
cursor = result['orders']['data']['pageInfo']['endCursor'] | |
if not result['orders']['data']['pageInfo']['hasNextPage']: | |
print("No more orders to fetch.") | |
break | |
except TransportQueryError as e: | |
error_data = e.errors[0] | |
print(f"Error occurred: {error_data}") | |
if error_data['code'] == 30: | |
print(f"Rate limit hit. Waiting for 120 seconds.") | |
time.sleep(120) | |
else: | |
raise e | |
except Exception as e: | |
print(f"An unexpected error occurred: {e}") | |
break | |
# Write all collected orders to a file | |
filename = 'orders-output.txt' | |
print(f"Writing all orders to {filename}") | |
with open(filename, 'w') as f: | |
f.write("Order Number,Fulfillment Status,Shop Name,Order Date,Tracking Number\n") | |
for order in all_orders: | |
f.write("{},{},{},{},{}\n".format(order['order_number'], order['fulfillment_status'], order['shop_name'], order['order_date'], order.get('tracking_number', 'N/A'))) | |
f.write(json.dumps(all_orders, indent=2)) | |
print("All orders have been fetched and written to files.") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment