import requests
import csv
import json
from datetime import datetime
API_KEY = "YOUR_API_KEY"
BASE_URL = "https://app.betterdata.co/api"
LOCATION_ID = "loc_123"
OUTPUT_FILE = f"inventory_snapshot_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv"
def fetch_all_inventory(location_id):
"""Fetch all inventory items across all pages."""
all_items = []
page = 1
while True:
url = f"{BASE_URL}/inventory"
headers = {
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json"
}
params = {
"locationId": location_id,
"page": page,
"limit": 100
}
response = requests.get(url, headers=headers, params=params)
response.raise_for_status()
data = response.json()
all_items.extend(data["items"])
total_pages = data["pagination"]["totalPages"]
if page >= total_pages:
break
page += 1
return all_items
def export_to_csv(items, filename):
"""Export inventory items to CSV."""
if not items:
print("No items to export")
return
# Define CSV columns
fieldnames = [
"productMasterId",
"productName",
"globalSku",
"locationId",
"locationName",
"quantityOnHand",
"quantityReserved",
"quantityAvailable",
"lotId",
"lotNumber",
"expiryDate",
"binId",
"binName",
"unitCost",
"totalValue",
"lastCountedAt",
"updatedAt"
]
with open(filename, 'w', newline='') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
for item in items:
# Flatten nested structures if needed
row = {
"productMasterId": item.get("productMasterId", ""),
"productName": item.get("productName", ""),
"globalSku": item.get("globalSku", ""),
"locationId": item.get("locationId", ""),
"locationName": item.get("locationName", ""),
"quantityOnHand": item.get("quantityOnHand", 0),
"quantityReserved": item.get("quantityReserved", 0),
"quantityAvailable": item.get("quantityAvailable", 0),
"lotId": item.get("lotId", ""),
"lotNumber": item.get("lotNumber", ""),
"expiryDate": item.get("expiryDate", ""),
"binId": item.get("binId", ""),
"binName": item.get("binName", ""),
"unitCost": item.get("unitCost", 0),
"totalValue": item.get("totalValue", 0),
"lastCountedAt": item.get("lastCountedAt", ""),
"updatedAt": item.get("updatedAt", "")
}
writer.writerow(row)
print(f"Exported {len(items)} items to {filename}")
if __name__ == "__main__":
print("Fetching inventory data...")
items = fetch_all_inventory(LOCATION_ID)
print(f"Fetched {len(items)} items")
print("Exporting to CSV...")
export_to_csv(items, OUTPUT_FILE)
print("Export complete")