JavaScript Examples

API Client Class

class DemiClient {
  constructor(apiKey) {
    this.apiKey = apiKey;
    this.baseUrl = 'https://api.getdemi.co/api/v1';
  }

  async request(endpoint, options = {}) {
    const response = await fetch(`${this.baseUrl}${endpoint}`, {
      ...options,
      headers: {
        'X-API-Key': this.apiKey,
        'Content-Type': 'application/json',
        ...options.headers,
      },
    });

    if (!response.ok) {
      const error = await response.json();
      throw new Error(error.error?.message || 'API Error');
    }

    return response.json();
  }

  // Products
  async listProducts(params = {}) {
    const query = new URLSearchParams(params).toString();
    return this.request(`/products${query ? '?' + query : ''}`);
  }

  async getProduct(id) {
    return this.request(`/products/${id}`);
  }

  // Customers
  async listCustomers(params = {}) {
    const query = new URLSearchParams(params).toString();
    return this.request(`/customers${query ? '?' + query : ''}`);
  }

  async createCustomer(data) {
    return this.request('/customers', {
      method: 'POST',
      body: JSON.stringify(data),
    });
  }

  async updateCustomer(id, data) {
    return this.request(`/customers/${id}`, {
      method: 'PATCH', // Both PUT and PATCH work for partial updates
      body: JSON.stringify(data),
    });
  }

  async updateOrder(id, data) {
    return this.request(`/orders/${id}`, {
      method: 'PATCH',
      body: JSON.stringify(data),
    });
  }

  // Orders
  async listOrders(params = {}) {
    const query = new URLSearchParams(params).toString();
    return this.request(`/orders${query ? '?' + query : ''}`);
  }

  async createOrder(data) {
    return this.request('/orders', {
      method: 'POST',
      body: JSON.stringify(data),
    });
  }
}

Usage Examples

Initialize Client

const client = new DemiClient(process.env.DEMI_API_KEY);

List Products

const products = await client.listProducts({ limit: 10 });
console.log(`Found ${products.total} products`);
products.data.forEach(p => console.log(p.name));

Create Customer

const customer = await client.createCustomer({
  name: 'Acme Corp',
  email: 'orders@acme.com',
  phone: '+1-555-123-4567',
  contactName: 'John Doe',
  paymentTerms: 'Net 30', // Optional: 'Due on receipt' (default), 'Net 15', 'Net 30', 'Net 60'
});
console.log(`Created customer: ${customer.id}`);

Update Customer (Partial Update)

const updated = await client.updateCustomer(123, {
  email: 'new-email@acme.com',
  phone: null, // Set to null to clear field
});
console.log(`Updated customer: ${updated.email}`);

Manage Customer Locations

// Create, update, and delete locations in one request
const updated = await client.updateCustomer(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 },
  ],
});
console.log(`Customer now has ${updated.locations.length} locations`);

Create Order

const order = await client.createOrder({
  customerId: 123,
  deliveryDate: '2024-01-15',
  items: [
    { productId: 42, quantity: 10 },
    { productId: 43, quantity: 5 },
  ],
});
console.log(`Created order: ${order.id}`);

Error Handling

try {
  const products = await client.listProducts();
} catch (error) {
  console.error('API Error:', error.message);
}

Other Languages