Python Examples

Installation

pip install requests

API Client Class

import requests
import os

class DemiClient:
    def __init__(self, api_key=None):
        self.api_key = api_key or os.environ.get('DEMI_API_KEY')
        self.base_url = 'https://api.getdemi.co/api/v1'
        self.session = requests.Session()
        self.session.headers.update({
            'X-API-Key': self.api_key,
            'Content-Type': 'application/json',
        })

    def _request(self, method, endpoint, **kwargs):
        url = f'{self.base_url}{endpoint}'
        response = self.session.request(method, url, **kwargs)
        response.raise_for_status()
        return response.json()

    # Products
    def list_products(self, limit=20, offset=0, search=None):
        params = {'limit': limit, 'offset': offset}
        if search:
            params['search'] = search
        return self._request('GET', '/products', params=params)

    def get_product(self, product_id):
        return self._request('GET', f'/products/{product_id}')

    # Customers
    def list_customers(self, limit=20, offset=0):
        return self._request('GET', '/customers', params={'limit': limit, 'offset': offset})

    def create_customer(self, name, email=None, phone=None, contact_name=None, payment_terms=None):
        data = {'name': name}
        if email: data['email'] = email
        if phone: data['phone'] = phone
        if contact_name: data['contactName'] = contact_name
        if payment_terms: data['paymentTerms'] = payment_terms
        return self._request('POST', '/customers', json=data)

    def update_customer(self, customer_id, **kwargs):
        # Both PUT and PATCH work for partial updates
        return self._request('PATCH', f'/customers/{customer_id}', json=kwargs)

    def delete_customer(self, customer_id):
        return self._request('DELETE', f'/customers/{customer_id}')

    def update_order(self, order_id, **kwargs):
        return self._request('PATCH', f'/orders/{order_id}', json=kwargs)

    # Orders
    def list_orders(self, limit=20, offset=0, customer_id=None, status=None):
        params = {'limit': limit, 'offset': offset}
        if customer_id: params['customerId'] = customer_id
        if status: params['status'] = status
        return self._request('GET', '/orders', params=params)

    def create_order(self, customer_id, delivery_date, items, po_number=None):
        data = {
            'customerId': customer_id,
            'deliveryDate': delivery_date,
            'items': items,
        }
        if po_number: data['poNumber'] = po_number
        return self._request('POST', '/orders', json=data)

    def cancel_order(self, order_id):
        return self._request('DELETE', f'/orders/{order_id}')

Usage Examples

# Initialize client
client = DemiClient()

# List products
products = client.list_products(limit=10)
print(f"Found {products['total']} products")
for product in products['data']:
    print(f"  - {product['name']}: ${product.get('priceRetail', 'N/A')}")

# Create customer
# paymentTerms options: 'Due on receipt' (default), 'Net 15', 'Net 30', 'Net 60'
customer = client.create_customer(
    name='Acme Corp',
    email='orders@acme.com',
    phone='+1-555-123-4567',
    contact_name='John Doe',
    payment_terms='Net 30'
)
print(f"Created customer: {customer['id']}")

# Update customer (partial update)
updated = client.update_customer(123, email='new-email@acme.com', phone=None)  # None clears field
print(f"Updated customer email: {updated['email']}")

# Manage customer locations
updated = client.update_customer(123, locations=[
    # Create new location (no id)
    {
        'name': 'Downtown Office',
        'address': {
            'address1': '123 Main St',
            'city': 'Vancouver',
            'countryDivision': 'BC',
            'country': 'CA',
            'postalCode': 'V5K 0A1'
        }
    },
    # Update existing location (with id)
    {'id': 456, 'name': 'Updated Location Name'},
    # Delete location (with id and _delete flag)
    {'id': 789, '_delete': True},
])
print(f"Customer now has {len(updated['locations'])} locations")

# Create order
order = client.create_order(
    customer_id=123,
    delivery_date='2024-01-15',
    items=[
        {'productId': 42, 'quantity': 10},
        {'productId': 43, 'quantity': 5},
    ]
)
print(f"Created order: {order['id']}")

Error Handling

from requests.exceptions import HTTPError

try:
    products = client.list_products()
except HTTPError as e:
    print(f"API Error: {e.response.status_code}")
    print(e.response.json())

Other Languages