Skip to main content
Follow these best practices to build reliable, secure integrations with the DHMAD API.

Security

Protect API Keys

Never commit API keys to version control. Use environment variables or secret management.

Use HTTPS

Always use HTTPS for all API requests in production.

Validate Input

Validate all user input before sending to the API.

Verify Webhooks

Always verify webhook signatures before processing.

Error Handling

Implement Retry Logic

async function apiCallWithRetry(fn, maxRetries = 3) {
  for (let i = 0; i < maxRetries; i++) {
    try {
      return await fn();
    } catch (error) {
      if (error.status === 429 || error.status >= 500) {
        await sleep(Math.pow(2, i) * 1000);
        continue;
      }
      throw error;
    }
  }
}

Log Errors

Always log errors for debugging:
try {
  await createEscrow(data);
} catch (error) {
  logger.error('Failed to create escrow', {
    error: error.message,
    data: sanitizeData(data) // Remove sensitive info
  });
  throw error;
}

Performance

Cache Responses

Cache frequently accessed data to reduce API calls

Batch Operations

Combine multiple operations when possible

Async Processing

Process webhooks asynchronously for quick responses

Monitor Usage

Track API usage to optimize requests

Code Organization

Separate Configuration

// config.js
export const API_CONFIG = {
  baseURL: process.env.DHMAD_API_URL || 'https://dhmad.tn/api/v1',
  apiKey: process.env.DHMAD_API_KEY,
  timeout: 30000
};

Create API Client

// apiClient.js
class DHMADClient {
  constructor(config) {
    this.baseURL = config.baseURL;
    this.apiKey = config.apiKey;
  }
  
  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) {
      throw new APIError(response);
    }
    
    return response.json();
  }
}

Testing

Use Test Environment

  • Use separate API keys for testing
  • Test all error scenarios
  • Verify webhook handling
  • Test rate limit handling

Mock API Responses

// In tests
jest.mock('./apiClient', () => ({
  createEscrow: jest.fn().mockResolvedValue({
    escrow: { id: 'test_123', status: 'pending' }
  })
}));

Monitoring

Track Key Metrics

  • API request success rate
  • Response times
  • Error rates by type
  • Rate limit usage

Set Up Alerts

  • Alert on high error rates
  • Alert on rate limit approaching
  • Alert on failed webhooks

Documentation

  • Document your integration
  • Keep API keys documented (securely)
  • Maintain changelog for API updates
  • Document error handling strategies

Following these best practices will help you build a reliable, maintainable integration with the DHMAD API.