Checking Inventory

Checking Inventory Guide

This guide explains how to query real-time inventory levels using the Spreetail Channel Integration API.

Overview

The inventory endpoint allows you to check stock availability, quantities, and product information in real-time. This is essential for:

  • Validating orders before creation
  • Displaying accurate stock levels to customers
  • Managing product availability
  • Planning restocking

Endpoint

GET /inventory

Full URL: https://api.spreetaileu.com/api/api/v1/inventory

Authentication

Requires Bearer token authentication. See the Authentication Guide for details.

Query Parameters

ParameterTypeRequiredDescription
skustringNoFilter by specific SKU
pageintegerNoPage number (default: 1)
limitintegerNoItems per page (default: 100, max: 1000)

Examples

Get All Inventory

GET https://api.spreetaileu.com/api/api/v1/inventory
Authorization: Bearer <your-token>

Get Specific SKU

GET https://api.spreetaileu.com/api/api/v1/inventory?sku=PROD-12345
Authorization: Bearer <your-token>

Paginated Results

GET https://api.spreetaileu.com/api/api/v1/inventory?page=1&limit=50
Authorization: Bearer <your-token>

Response Format

Success Response (200)

{
  "success": true,
  "data": {
    "items": [
      {
        "sku": "PROD-12345",
        "title": "Premium Wireless Headphones",
        "quantity": 150,
        "available": true,
        "reserved": 5,
        "on_hand": 155,
        "last_updated": "2025-01-15T10:30:00Z"
      },
      {
        "sku": "PROD-67890",
        "title": "USB-C Cable",
        "quantity": 0,
        "available": false,
        "reserved": 0,
        "on_hand": 0,
        "last_updated": "2025-01-15T09:15:00Z"
      }
    ],
    "pagination": {
      "page": 1,
      "limit": 100,
      "total": 250,
      "total_pages": 3
    }
  }
}

Response Fields

FieldTypeDescription
skustringProduct SKU identifier
titlestringProduct title/name
quantityintegerAvailable quantity (on_hand - reserved)
availablebooleanWhether product is in stock
reservedintegerQuantity reserved for pending orders
on_handintegerTotal quantity in warehouse
last_updatedstring (ISO 8601)Last inventory update timestamp

Code Examples

Python

import requests

def get_inventory(access_token, sku=None, page=1, limit=100):
    """Get inventory information"""
    url = "https://api.spreetaileu.com/api/api/v1/inventory"
    headers = {
        "Authorization": f"Bearer {access_token}"
    }
    params = {}
    
    if sku:
        params['sku'] = sku
    if page:
        params['page'] = page
    if limit:
        params['limit'] = limit
    
    response = requests.get(url, headers=headers, params=params)
    response.raise_for_status()
    return response.json()

# Get all inventory
inventory = get_inventory(access_token)
print(f"Total items: {inventory['data']['pagination']['total']}")

# Get specific SKU
product = get_inventory(access_token, sku="PROD-12345")
if product['data']['items']:
    item = product['data']['items'][0]
    print(f"{item['sku']}: {item['quantity']} available")

JavaScript/Node.js

async function getInventory(accessToken, options = {}) {
  const { sku, page = 1, limit = 100 } = options;
  const url = new URL('https://api.spreetaileu.com/api/api/v1/inventory');
  
  if (sku) url.searchParams.append('sku', sku);
  if (page) url.searchParams.append('page', page);
  if (limit) url.searchParams.append('limit', limit);
  
  const response = await fetch(url, {
    headers: {
      'Authorization': `Bearer ${accessToken}`
    }
  });
  
  if (!response.ok) {
    const error = await response.json();
    throw new Error(`Inventory check failed: ${error.error || response.statusText}`);
  }
  
  return await response.json();
}

// Get all inventory
const inventory = await getInventory(accessToken);
console.log(`Total items: ${inventory.data.pagination.total}`);

// Get specific SKU
const product = await getInventory(accessToken, { sku: 'PROD-12345' });
if (product.data.items.length > 0) {
  const item = product.data.items[0];
  console.log(`${item.sku}: ${item.quantity} available`);
}

Use Cases

1. Validate Order Before Creation

def validate_order_items(access_token, order_items):
    """Check if all order items are in stock"""
    unavailable_items = []
    
    for item in order_items:
        inventory = get_inventory(access_token, sku=item['SKU'])
        
        if not inventory['data']['items']:
            unavailable_items.append({
                'sku': item['SKU'],
                'reason': 'SKU not found'
            })
        elif inventory['data']['items'][0]['quantity'] < item['Qty']:
            unavailable_items.append({
                'sku': item['SKU'],
                'reason': f"Insufficient stock. Available: {inventory['data']['items'][0]['quantity']}, Required: {item['Qty']}"
            })
    
    return unavailable_items

# Before creating order
order_items = [
    {'SKU': 'PROD-12345', 'Qty': 2},
    {'SKU': 'PROD-67890', 'Qty': 1}
]

issues = validate_order_items(access_token, order_items)
if issues:
    print("Cannot create order - stock issues:")
    for issue in issues:
        print(f"  {issue['sku']}: {issue['reason']}")
else:
    print("All items in stock - proceeding with order creation")

2. Monitor Low Stock

def check_low_stock(access_token, threshold=10):
    """Find items with low stock levels"""
    inventory = get_inventory(access_token, limit=1000)
    low_stock_items = []
    
    for item in inventory['data']['items']:
        if item['quantity'] <= threshold:
            low_stock_items.append(item)
    
    return low_stock_items

low_stock = check_low_stock(access_token, threshold=10)
if low_stock:
    print(f"Warning: {len(low_stock)} items below threshold")
    for item in low_stock:
        print(f"  {item['sku']}: {item['quantity']} remaining")

3. Batch Inventory Check

def batch_check_inventory(access_token, sku_list):
    """Check inventory for multiple SKUs efficiently"""
    results = {}
    
    for sku in sku_list:
        inventory = get_inventory(access_token, sku=sku)
        if inventory['data']['items']:
            results[sku] = inventory['data']['items'][0]
        else:
            results[sku] = None
    
    return results

# Check multiple SKUs
skus = ['PROD-12345', 'PROD-67890', 'PROD-11111']
inventory_status = batch_check_inventory(access_token, skus)

for sku, data in inventory_status.items():
    if data:
        print(f"{sku}: {data['quantity']} available")
    else:
        print(f"{sku}: Not found")

Pagination

When dealing with large inventories, use pagination:

def get_all_inventory(access_token):
    """Retrieve all inventory items across all pages"""
    all_items = []
    page = 1
    
    while True:
        inventory = get_inventory(access_token, page=page, limit=100)
        items = inventory['data']['items']
        all_items.extend(items)
        
        pagination = inventory['data']['pagination']
        if page >= pagination['total_pages']:
            break
        
        page += 1
    
    return all_items

# Get complete inventory
complete_inventory = get_all_inventory(access_token)
print(f"Total SKUs: {len(complete_inventory)}")

Error Handling

def safe_get_inventory(access_token, sku=None):
    """Get inventory with error handling"""
    try:
        return get_inventory(access_token, sku=sku)
    except requests.exceptions.HTTPError as e:
        if e.response.status_code == 401:
            raise Exception("Authentication failed. Token may be expired.")
        elif e.response.status_code == 404:
            return {"success": True, "data": {"items": []}}
        else:
            raise Exception(f"Inventory check failed: {e}")

Best Practices

  1. Cache Results: Inventory data can be cached for a few minutes to reduce API calls
  2. Check Before Orders: Always validate stock before creating orders
  3. Handle Pagination: Use pagination for large inventories
  4. Monitor Updates: Check last_updated timestamp to ensure data freshness
  5. Respect Rate Limits: Don't poll inventory too frequently

Rate Limits

  • Standard rate limit: 100 requests per minute per client
  • For high-volume needs, contact [email protected]

Related Endpoints

  • POST /outbound - Create orders (check inventory first)
  • POST /inbound - Register inbound deliveries (affects inventory)