Skip to content

Instantly share code, notes, and snippets.

@BFTrick
Last active October 21, 2024 16:45
Show Gist options
  • Save BFTrick/83f44f65ae30bb078b51e17f583d2682 to your computer and use it in GitHub Desktop.
Save BFTrick/83f44f65ae30bb078b51e17f583d2682 to your computer and use it in GitHub Desktop.
#!/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 = """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 = gql(query_template)
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, 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
# Example usage
order_id = "517111404"
tracking_number = get_tracking_number(order_id)
if tracking_number:
print(f"Tracking number for order {order_id}: {tracking_number}")
else:
print(f"No tracking number found for order {order_id}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment