Technology

API Integration Best Practices

A comprehensive guide to integrating Efimart APIs with your existing systems for seamless data flow and automation.

David Kimani
November 20, 2023 8 min read

API integrations are the backbone of modern business operations, enabling seamless data flow between systems and automated workflows. This comprehensive guide covers everything you need to know about integrating with Efimart's APIs to maximize efficiency and minimize development overhead.

💡 Before You Start

This guide assumes basic familiarity with REST APIs and JSON. If you're new to APIs, consider reviewing our Getting Started guide first.

Understanding Efimart's API Architecture

Efimart's API follows RESTful principles and is organized around key business objects: orders, products, customers, and inventory. Our API is designed to be predictable, resource-oriented URLs, accepts JSON-encoded request bodies, and returns JSON-encoded responses.

Core API Endpoints

Orders API

  • GET /api/v1/orders - List orders
  • POST /api/v1/orders - Create order
  • GET /api/v1/orders/{}id{'} - Get order details
  • PATCH /api/v1/orders/{}id{'} - Update order

Products API

  • GET /api/v1/products - List products
  • POST /api/v1/products - Create product
  • GET /api/v1/products/{}id{'} - Get product
  • PATCH /api/v1/products/{}id{'} - Update product

Customers API

  • GET /api/v1/customers - List customers
  • POST /api/v1/customers - Create customer
  • GET /api/v1/customers/{}id{'} - Get customer
  • PATCH /api/v1/customers/{}id{'} - Update customer

Inventory API

  • GET /api/v1/inventory - List inventory
  • POST /api/v1/inventory/adjust - Adjust stock
  • GET /api/v1/inventory/{}id{'} - Get stock levels
  • GET /api/v1/inventory/movements - Stock movements

Authentication and Security

API Key Authentication

Efimart uses API key authentication. All API requests must include your API key in the Authorization header:

Authorization: Bearer your_api_key_here

🔒 Security Best Practices

  • • Never expose API keys in client-side code
  • • Store API keys in environment variables
  • • Use different API keys for different environments
  • • Regularly rotate your API keys
  • • Implement proper error handling to avoid key exposure
  • • Use HTTPS for all API requests

Rate Limiting

Our APIs implement rate limiting to ensure fair usage and system stability:

📊 Rate Limits by Plan

Starter
1,000 requests/hour
Professional
10,000 requests/hour
Enterprise
100,000 requests/hour

Integration Patterns and Use Cases

Real-time Synchronization

For businesses requiring real-time data synchronization, implement webhook listeners and use our real-time endpoints:

// Example: Real-time order creation
const createOrder = async (orderData) => {
  try {
    const response = await fetch('https://api.efimart.co/v1/orders', {
      method: 'POST',
      headers: {
        'Authorization': 'Bearer ' + process.env.EFIMART_API_KEY,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(orderData)
    });
    
    if (!response.ok) {
      throw new Error('Failed to create order');
    }
    
    const order = await response.json();
    return order;
  } catch (error) {
    console.error('Order creation failed:', error);
    throw error;
  }
};

Batch Processing

For bulk operations, use our batch endpoints to reduce API calls and improve performance:

// Example: Batch product update
const updateProductsBatch = async (products) => {
  const batchSize = 100;
  const results = [];
  
  for (let i = 0; i < products.length; i += batchSize) {
    const batch = products.slice(i, i + batchSize);
    
    try {
      const response = await fetch('https://api.efimart.co/v1/products/batch', {
        method: 'PATCH',
        headers: {
          'Authorization': 'Bearer ' + process.env.EFIMART_API_KEY,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ products: batch })
      });
      
      const result = await response.json();
      results.push(...result.updated);
      
      // Respect rate limits
      await new Promise(resolve => setTimeout(resolve, 1000));
    } catch (error) {
      console.error('Batch update failed for batch starting at', i, error);
    }
  }
  
  return results;
};

Error Handling and Resilience

HTTP Status Codes

Efimart APIs use standard HTTP status codes to indicate the success or failure of requests:

✅ Success Codes

  • 200 OK: Request successful
  • 201 Created: Resource created
  • 204 No Content: Request successful, no data returned

❌ Error Codes

  • 400 Bad Request: Invalid request data
  • 401 Unauthorized: Invalid or missing API key
  • 404 Not Found: Resource doesn't exist
  • 429 Too Many Requests: Rate limit exceeded
  • 500 Internal Server Error: Server error

Implementing Retry Logic

Robust integrations should handle temporary failures gracefully:

// Example: Exponential backoff retry logic
const makeApiRequestWithRetry = async (url, options, maxRetries = 3) => {
  for (let attempt = 1; attempt <= maxRetries; attempt++) {
    try {
      const response = await fetch(url, options);
      
      // If rate limited, wait and retry
      if (response.status === 429) {
        const retryAfter = response.headers.get('Retry-After') || Math.pow(2, attempt);
        await new Promise(resolve => setTimeout(resolve, retryAfter * 1000));
        continue;
      }
      
      // If server error, retry with backoff
      if (response.status >= 500 && attempt < maxRetries) {
        await new Promise(resolve => setTimeout(resolve, Math.pow(2, attempt) * 1000));
        continue;
      }
      
      return response;
    } catch (error) {
      if (attempt === maxRetries) {
        throw error;
      }
      
      // Wait before retrying
      await new Promise(resolve => setTimeout(resolve, Math.pow(2, attempt) * 1000));
    }
  }
};

Webhook Integration

Setting Up Webhooks

Webhooks enable real-time notifications when events occur in your Efimart account:

🔗 Available Webhook Events

  • order.created: New order placed
  • order.updated: Order status changed
  • inventory.low: Stock below threshold
  • payment.received: Payment processed
  • customer.created: New customer registered
// Example: Webhook endpoint handler
app.post('/webhooks/efimart', express.raw({type: 'application/json'}), (req, res) => {
  const signature = req.headers['x-efimart-signature'];
  const payload = req.body;
  
  // Verify webhook signature
  const expectedSignature = crypto
    .createHmac('sha256', process.env.WEBHOOK_SECRET)
    .update(payload, 'utf8')
    .digest('hex');
  
  if (signature !== expectedSignature) {
    return res.status(401).send('Unauthorized');
  }
  
  const event = JSON.parse(payload);
  
  switch (event.type) {
    case 'order.created':
      handleNewOrder(event.data);
      break;
    case 'inventory.low':
      handleLowInventory(event.data);
      break;
    default:
      console.log('Unhandled event type:', event.type);
  }
  
  res.status(200).send('OK');
});

Performance Optimization

Caching Strategies

Implement intelligent caching to reduce API calls and improve response times:

📦 Product Data

  • • Cache product catalogs for 1-4 hours
  • • Use ETags for conditional requests
  • • Implement cache invalidation on updates

👥 Customer Data

  • • Cache customer profiles for sessions
  • • Use local storage for recent customers
  • • Refresh on user-triggered actions

Pagination and Filtering

Use pagination and filtering to minimize data transfer and improve performance:

// Example: Efficient data fetching with pagination
const fetchOrdersEfficiently = async (filters = {}, page = 1, limit = 50) => {
  const queryParams = new URLSearchParams({
    page,
    limit,
    ...filters,
    fields: 'id,status,customer_id,total,created_at' // Only fetch needed fields
  });
  
  const response = await fetch(
    `https://api.efimart.co/v1/orders?${queryParams}`,
    {
      headers: {
        'Authorization': 'Bearer ' + process.env.EFIMART_API_KEY,
        'Accept': 'application/json',
        'If-None-Match': localStorage.getItem('orders-etag') // Use ETags
      }
    }
  );
  
  if (response.status === 304) {
    // Data hasn't changed, use cached version
    return JSON.parse(localStorage.getItem('orders-cache'));
  }
  
  const data = await response.json();
  
  // Cache the response
  localStorage.setItem('orders-cache', JSON.stringify(data));
  localStorage.setItem('orders-etag', response.headers.get('ETag'));
  
  return data;
};

Testing and Debugging

API Testing Environment

Use our sandbox environment for testing and development:

🧪 Sandbox Details

  • • Base URL: https://sandbox-api.efimart.co
  • • Separate API keys for sandbox testing
  • • Test data is reset daily
  • • All API endpoints available
  • • Webhook testing supported

Logging and Monitoring

Implement comprehensive logging for debugging and monitoring:

// Example: Comprehensive API logging
const logApiRequest = (method, url, requestData, response, duration) => {
  const logData = {
    timestamp: new Date().toISOString(),
    method,
    url: url.replace(/api_key=[^&]+/, 'api_key=***'), // Hide API key
    status: response.status,
    duration: duration + 'ms',
    requestId: response.headers.get('X-Request-ID'),
    rateLimitRemaining: response.headers.get('X-RateLimit-Remaining')
  };
  
  if (!response.ok) {
    logData.error = response.statusText;
    logData.requestBody = JSON.stringify(requestData);
  }
  
  console.log('API Request:', JSON.stringify(logData));
  
  // Send to monitoring service
  sendToMonitoring(logData);
};

Common Integration Patterns

ERP System Integration

Common pattern for connecting ERP systems with Efimart:

📊 Data Synchronization Flow

  1. 1. Products: ERP → Efimart (nightly sync)
  2. 2. Inventory: ERP → Efimart (every 15 minutes)
  3. 3. Orders: Efimart → ERP (real-time via webhooks)
  4. 4. Customers: Bi-directional (conflict resolution needed)

E-commerce Platform Integration

For businesses with online stores, synchronize data between your e-commerce platform and Efimart:

🛒 Integration Points

  • • Product catalog synchronization
  • • Real-time inventory updates
  • • Order fulfillment tracking
  • • Customer data unification
  • • Pricing and promotions sync

Advanced Features

GraphQL Support

For complex queries and data relationships, use our GraphQL endpoint:

query GetOrderWithDetails($orderId: ID!) {
  order(id: $orderId) {
    id
    status
    total
    customer {
      id
      name
      email
    }
    items {
      product {
        id
        name
        sku
      }
      quantity
      price
    }
    payments {
      id
      amount
      status
      method
    }
  }
}

Real-time Subscriptions

Use WebSocket subscriptions for real-time updates:

// Example: WebSocket subscription for inventory updates
const ws = new WebSocket('wss://api.efimart.co/subscriptions', {
  headers: {
    'Authorization': 'Bearer ' + process.env.EFIMART_API_KEY
  }
});

ws.on('open', () => {
  ws.send(JSON.stringify({
    type: 'subscribe',
    channel: 'inventory.updates',
    filters: { warehouse_id: '123' }
  }));
});

ws.on('message', (data) => {
  const update = JSON.parse(data);
  if (update.type === 'inventory.updated') {
    updateLocalInventory(update.data);
  }
});

Integration Checklist

✅ Pre-Integration Checklist

  • □ Obtain API credentials for all environments
  • □ Review API documentation and rate limits
  • □ Design data mapping and transformation logic
  • □ Set up error handling and logging
  • □ Implement authentication and security measures
  • □ Plan data synchronization strategy
  • □ Set up monitoring and alerting
  • □ Create comprehensive tests
  • □ Document integration architecture
  • □ Plan rollback procedures

Getting Help and Support

Our developer support team is here to help you succeed with your integration:

📚 Resources

💬 Support Channels

  • • Email: developers@efimart.com
  • • Slack community
  • • Video consultation sessions
  • • Priority support for Enterprise

Successful API integration requires careful planning, robust error handling, and ongoing maintenance. By following these best practices and leveraging Efimart's comprehensive API features, you can build reliable, efficient integrations that scale with your business needs.

Ready to Start Your Integration?

Get your API credentials and start building with Efimart today