Skip to main content

API Usage Best Practices

Best practices for using the O2VEND Storefront API.

Authentication

Secure API Key Storage

// ❌ Don't expose API keys
const apiKey = 'your-api-key';

// ✅ Use environment variables
const apiKey = process.env.O2VEND_API_KEY;

Token Management

// Implement token refresh
async function getValidToken() {
if (isTokenExpired(token)) {
token = await refreshToken();
}
return token;
}

Request Optimization

Batch Requests

// ❌ Multiple requests
const products = await api.getProducts();
const categories = await api.getCategories();

// ✅ Batch request
const data = await api.batch({
products: '/products',
categories: '/categories'
});

Implement Caching

const cache = new Map();

async function getCachedData(key, fetcher) {
if (cache.has(key)) {
return cache.get(key);
}
const data = await fetcher();
cache.set(key, data);
return data;
}

Error Handling

Comprehensive Error Handling

try {
const response = await api.getProducts();
} catch (error) {
if (error.response?.status === 401) {
// Handle authentication error
} else if (error.response?.status === 429) {
// Handle rate limit
} else {
// Handle other errors
}
}

Rate Limiting

Implement Rate Limiting

class RateLimiter {
constructor(maxRequests, windowMs) {
this.maxRequests = maxRequests;
this.windowMs = windowMs;
this.requests = [];
}

async checkLimit() {
const now = Date.now();
this.requests = this.requests.filter(
time => now - time < this.windowMs
);

if (this.requests.length >= this.maxRequests) {
throw new Error('Rate limit exceeded');
}

this.requests.push(now);
}
}