Api Reference
This guide shows you how to export inventory snapshot data for reporting and analysis.
inventory.read permissionRetrieve inventory items with pagination to handle large datasets.
Request:
1curl -X GET "https://app.betterdata.co/api/inventory?locationId=loc_123&page=1&limit=100" \2 -H "Authorization: Bearer YOUR_API_KEY" \3 -H "Content-Type: application/json"Response:
1{2 "items": [3 {4 "id": "item_123",5 "productMasterId": "prod_123",6 "productName": "Product Name",7 "globalSku": "SKU-123",8 "locationId": "loc_123",9 "locationName": "Main Warehouse",10 "quantityOnHand": 200,11 "quantityReserved": 50,12 "quantityAvailable": 150,13 "lotId": "lot_123",14 "lotNumber": "LOT-2024-001",15 "expiryDate": "2024-12-31",16 "binId": "bin_123",17 "binName": "A-1-2",18 "unitCost": 10.50,19 "totalValue": 2100.00,20 "lastCountedAt": "2024-03-01T00:00:00Z",21 "updatedAt": "2024-03-15T00:00:00Z"22 }23 ],24 "pagination": {25 "page": 1,26 "pageSize": 100,27 "total": 500,28 "totalPages": 529 }30}Iterate through all pages to get complete inventory snapshot.
Example Script:
1#!/bin/bash2 3API_KEY="YOUR_API_KEY"4BASE_URL="https://app.betterdata.co/api"5LOCATION_ID="loc_123"6OUTPUT_FILE="inventory_snapshot.json"7 8# Initialize output array9echo "[]" > $OUTPUT_FILE10 11# Fetch all pages12PAGE=113while true; do14 echo "Fetching page $PAGE..."15 16 RESPONSE=$(curl -s -X GET "${BASE_URL}/inventory?locationId=${LOCATION_ID}&page=${PAGE}&limit=100" \17 -H "Authorization: Bearer ${API_KEY}" \18 -H "Content-Type: application/json")19 20 # Extract items and append to output21 ITEMS=$(echo $RESPONSE | jq -r '.items[]')22 if [ -z "$ITEMS" ]; then23 break24 fi25 26 # Merge items into output file27 jq --argjson items "$(echo $RESPONSE | jq '.items')" '. += $items' $OUTPUT_FILE > ${OUTPUT_FILE}.tmp28 mv ${OUTPUT_FILE}.tmp $OUTPUT_FILE29 30 # Check if more pages31 TOTAL_PAGES=$(echo $RESPONSE | jq -r '.pagination.totalPages')32 if [ $PAGE -ge $TOTAL_PAGES ]; then33 break34 fi35 36 PAGE=$((PAGE + 1))37done38 39echo "Export complete: $(jq 'length' $OUTPUT_FILE) items exported to $OUTPUT_FILE"Export ATP data across channels and locations.
Request:
1curl -X GET "https://app.betterdata.co/api/inventory/channel-location?locationId=loc_123&page=1&limit=100" \2 -H "Authorization: Bearer YOUR_API_KEY" \3 -H "Content-Type: application/json"Response:
1{2 "products": [3 {4 "productMasterId": "prod_123",5 "productName": "Product Name",6 "globalSku": "SKU-123",7 "channels": [8 {9 "channelId": "DTC",10 "channelName": "Direct to Consumer",11 "atp": 150,12 "onHand": 200,13 "reserved": 50,14 "available": 15015 }16 ],17 "totalOnHand": 200,18 "totalReserved": 50,19 "minAtp": 150,20 "maxAtp": 15021 }22 ],23 "pagination": {24 "page": 1,25 "pageSize": 100,26 "total": 500,27 "totalPages": 528 }29}Convert JSON export to CSV format for reporting.
Python Example:
1import requests2import csv3import json4from datetime import datetime5 6API_KEY = "YOUR_API_KEY"7BASE_URL = "https://app.betterdata.co/api"8LOCATION_ID = "loc_123"9OUTPUT_FILE = f"inventory_snapshot_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv"10 11def fetch_all_inventory(location_id):12 """Fetch all inventory items across all pages."""13 all_items = []14 page = 115 16 while True:17 url = f"{BASE_URL}/inventory"18 headers = {19 "Authorization": f"Bearer {API_KEY}",20 "Content-Type": "application/json"21 }22 params = {23 "locationId": location_id,24 "page": page,25 "limit": 10026 }27 28 response = requests.get(url, headers=headers, params=params)29 response.raise_for_status()30 data = response.json()31 32 all_items.extend(data["items"])33 34 total_pages = data["pagination"]["totalPages"]35 if page >= total_pages:36 break37 page += 138 39 return all_items40 41def export_to_csv(items, filename):42 """Export inventory items to CSV."""43 if not items:44 print("No items to export")45 return46 47 # Define CSV columns48 fieldnames = [49 "productMasterId",50 "productName",51 "globalSku",52 "locationId",53 "locationName",54 "quantityOnHand",55 "quantityReserved",56 "quantityAvailable",57 "lotId",58 "lotNumber",59 "expiryDate",60 "binId",61 "binName",62 "unitCost",63 "totalValue",64 "lastCountedAt",65 "updatedAt"66 ]67 68 with open(filename, 'w', newline='') as csvfile:69 writer = csv.DictWriter(csvfile, fieldnames=fieldnames)70 writer.writeheader()71 72 for item in items:73 # Flatten nested structures if needed74 row = {75 "productMasterId": item.get("productMasterId", ""),76 "productName": item.get("productName", ""),77 "globalSku": item.get("globalSku", ""),78 "locationId": item.get("locationId", ""),79 "locationName": item.get("locationName", ""),80 "quantityOnHand": item.get("quantityOnHand", 0),81 "quantityReserved": item.get("quantityReserved", 0),82 "quantityAvailable": item.get("quantityAvailable", 0),83 "lotId": item.get("lotId", ""),84 "lotNumber": item.get("lotNumber", ""),85 "expiryDate": item.get("expiryDate", ""),86 "binId": item.get("binId", ""),87 "binName": item.get("binName", ""),88 "unitCost": item.get("unitCost", 0),89 "totalValue": item.get("totalValue", 0),90 "lastCountedAt": item.get("lastCountedAt", ""),91 "updatedAt": item.get("updatedAt", "")92 }93 writer.writerow(row)94 95 print(f"Exported {len(items)} items to {filename}")96 97if __name__ == "__main__":98 print("Fetching inventory data...")99 items = fetch_all_inventory(LOCATION_ID)100 print(f"Fetched {len(items)} items")101 102 print("Exporting to CSV...")103 export_to_csv(items, OUTPUT_FILE)104 print("Export complete")Export aggregated inventory analytics.
Request:
1curl -X GET "https://app.betterdata.co/api/inventory/analytics?locationId=loc_123&fromDate=2024-01-01&toDate=2024-12-31" \2 -H "Authorization: Bearer YOUR_API_KEY" \3 -H "Content-Type: application/json"Response:
1{2 "analytics": {3 "totalValue": 50000.00,4 "totalUnits": 1000,5 "turnoverRate": 12.5,6 "averageDaysOnHand": 30,7 "slowMovingItems": 25,8 "expiringItems": 10,9 "byCategory": [10 {11 "categoryId": "cat_123",12 "categoryName": "Category",13 "value": 25000.00,14 "units": 50015 }16 ]17 },18 "period": {19 "from": "2024-01-01T00:00:00Z",20 "to": "2024-12-31T23:59:59Z"21 }22}Here's a complete Python script for inventory export:
1import requests2import csv3import json4from datetime import datetime5from typing import List, Dict6 7API_KEY = "YOUR_API_KEY"8BASE_URL = "https://app.betterdata.co/api"9 10class InventoryExporter:11 def __init__(self, api_key: str):12 self.api_key = api_key13 self.headers = {14 "Authorization": f"Bearer {api_key}",15 "Content-Type": "application/json"16 }17 18 def fetch_all_pages(self, endpoint: str, params: Dict) -> List[Dict]:19 """Fetch all pages from a paginated endpoint."""20 all_items = []21 page = 122 23 while True:24 params["page"] = page25 response = requests.get(f"{BASE_URL}/{endpoint}", headers=self.headers, params=params)26 response.raise_for_status()27 data = response.json()28 29 items_key = "items" if "items" in data else "products" if "products" in data else "data"30 items = data.get(items_key, [])31 all_items.extend(items)32 33 pagination = data.get("pagination", {})34 total_pages = pagination.get("totalPages", 1)35 36 if page >= total_pages:37 break38 page += 139 40 return all_items41 42 def export_inventory(self, location_id: str = None, output_format: str = "csv") -> str:43 """Export inventory snapshot."""44 params = {"limit": 100}45 if location_id:46 params["locationId"] = location_id47 48 print("Fetching inventory data...")49 items = self.fetch_all_pages("inventory", params)50 print(f"Fetched {len(items)} items")51 52 timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")53 54 if output_format == "csv":55 filename = f"inventory_snapshot_{timestamp}.csv"56 self._export_to_csv(items, filename)57 else:58 filename = f"inventory_snapshot_{timestamp}.json"59 self._export_to_json(items, filename)60 61 return filename62 63 def _export_to_csv(self, items: List[Dict], filename: str):64 """Export items to CSV."""65 if not items:66 print("No items to export")67 return68 69 fieldnames = [70 "productMasterId", "productName", "globalSku",71 "locationId", "locationName",72 "quantityOnHand", "quantityReserved", "quantityAvailable",73 "lotId", "lotNumber", "expiryDate",74 "binId", "binName",75 "unitCost", "totalValue",76 "lastCountedAt", "updatedAt"77 ]78 79 with open(filename, 'w', newline='') as csvfile:80 writer = csv.DictWriter(csvfile, fieldnames=fieldnames, extrasaction='ignore')81 writer.writeheader()82 writer.writerows(items)83 84 print(f"Exported {len(items)} items to {filename}")85 86 def _export_to_json(self, items: List[Dict], filename: str):87 """Export items to JSON."""88 with open(filename, 'w') as f:89 json.dump({90 "exportedAt": datetime.now().isoformat(),91 "totalItems": len(items),92 "items": items93 }, f, indent=2)94 95 print(f"Exported {len(items)} items to {filename}")96 97if __name__ == "__main__":98 exporter = InventoryExporter(API_KEY)99 filename = exporter.export_inventory(location_id="loc_123", output_format="csv")100 print(f"Export complete: {filename}")page and limit (default: 20, max: 100).page and limit (default: 50, max: 200).Symptom: Export missing some inventory items.
Solutions:
totalPages in pagination)Symptom: Export takes too long to complete.
Solutions:
limit parameter to fetch more items per pageSymptom: Script runs out of memory during export.
Solutions:
Inventory export requires inventory.read permission. No special roles required beyond basic authentication.
