API Examples
Practical examples for using the O2VEND Storefront API in different scenarios.
Setup
JavaScript/Node.js
const axios = require('axios');
const apiClient = axios.create({
baseURL: 'https://your-store.o2vend.com/shopfront/api/v2',
headers: {
'X-O2VEND-SHOPFRONT-API-KEY': 'your-api-key-here',
'Content-Type': 'application/json'
}
});
Python
import requests
API_KEY = 'your-api-key-here'
BASE_URL = 'https://your-store.o2vend.com/shopfront/api/v2'
headers = {
'X-O2VEND-SHOPFRONT-API-KEY': API_KEY,
'Content-Type': 'application/json'
}
Product Examples
Fetch Products
Try this API endpoint interactively:
Try It Out
Fetch a list of products with pagination and filters
POST/shopfront/api/v2/productsJavaScript:
async function getProducts() {
try {
const response = await apiClient.post('/products', {
page: 1,
pageSize: 20,
filters: {
available: true
}
});
return response.data;
} catch (error) {
console.error('Error fetching products:', error);
throw error;
}
}
Python:
def get_products():
response = requests.post(
f'{BASE_URL}/products',
json={
'page': 1,
'pageSize': 20,
'filters': {
'available': True
}
},
headers=headers
)
return response.json()
Get Single Product
JavaScript:
async function getProduct(productId) {
try {
const response = await apiClient.get(`/products/${productId}`);
return response.data;
} catch (error) {
console.error('Error fetching product:', error);
throw error;
}
}
Cart Examples
Add to Cart
Try this API endpoint interactively:
Try It Out
Add a product to the shopping cart
POST/shopfront/api/v2/cart/itemsJavaScript:
async function addToCart(productId, variantId, quantity = 1) {
try {
const response = await apiClient.post('/cart/items', {
productId,
variantId,
quantity
});
return response.data;
} catch (error) {
console.error('Error adding to cart:', error);
throw error;
}
}
// Usage
await addToCart('prod-123', 'var-456', 2);
Python:
def add_to_cart(product_id, variant_id, quantity=1):
response = requests.post(
f'{BASE_URL}/cart/items',
json={
'productId': product_id,
'variantId': variant_id,
'quantity': quantity
},
headers=headers
)
return response.json()
Update Cart Item
JavaScript:
async function updateCartItem(itemId, quantity) {
try {
const response = await apiClient.put(`/cart/items/${itemId}`, {
quantity
});
return response.data;
} catch (error) {
console.error('Error updating cart:', error);
throw error;
}
}
Get Cart
JavaScript:
async function getCart() {
try {
const response = await apiClient.get('/cart');
return response.data;
} catch (error) {
console.error('Error fetching cart:', error);
throw error;
}
}
Checkout Examples
Create Checkout
JavaScript:
const crypto = require('crypto');
function generateCheckoutSignature(requestBody, secretKey) {
const hmac = crypto.createHmac('sha256', secretKey);
hmac.update(JSON.stringify(requestBody));
return hmac.digest('base64');
}
async function createCheckout(cartId, shippingAddress, billingAddress) {
const checkoutData = {
cartId,
shippingAddress,
billingAddress,
paymentMethod: 'razorpay'
};
const signature = generateCheckoutSignature(
checkoutData,
process.env.CHECKOUT_SECRET
);
try {
const response = await apiClient.post('/checkout', checkoutData, {
headers: {
'X-CHECKOUT-SIGNATURE': signature
}
});
return response.data;
} catch (error) {
console.error('Error creating checkout:', error);
throw error;
}
}
Complete Checkout
JavaScript:
async function completeCheckout(checkoutId, paymentId, signature) {
try {
const response = await apiClient.post(
`/checkout/${checkoutId}/complete`,
{
paymentId,
paymentSignature: signature
}
);
return response.data;
} catch (error) {
console.error('Error completing checkout:', error);
throw error;
}
}
Search Examples
Search Products
JavaScript:
async function searchProducts(query, filters = {}) {
try {
const response = await apiClient.post('/search', {
query,
filters,
page: 1,
pageSize: 20
});
return response.data;
} catch (error) {
console.error('Error searching:', error);
throw error;
}
}
// Usage
const results = await searchProducts('laptop', {
priceMin: 10000,
priceMax: 50000
});
Collection Examples
Get Collection Products
JavaScript:
async function getCollectionProducts(collectionId) {
try {
const response = await apiClient.get(`/collections/${collectionId}`);
return response.data.products;
} catch (error) {
console.error('Error fetching collection:', error);
throw error;
}
}
Error Handling
Comprehensive Error Handling
JavaScript:
async function apiRequest(endpoint, method = 'GET', data = null) {
try {
const config = {
method,
url: endpoint,
headers: {
'X-O2VEND-SHOPFRONT-API-KEY': API_KEY,
'Content-Type': 'application/json'
}
};
if (data) {
config.data = data;
}
const response = await apiClient(config);
return response.data;
} catch (error) {
if (error.response) {
// Server responded with error
console.error('API Error:', error.response.status);
console.error('Error Data:', error.response.data);
switch (error.response.status) {
case 401:
throw new Error('Authentication failed');
case 404:
throw new Error('Resource not found');
case 429:
throw new Error('Rate limit exceeded');
default:
throw new Error(error.response.data.error || 'API request failed');
}
} else if (error.request) {
// Request made but no response
throw new Error('No response from server');
} else {
// Error in request setup
throw new Error('Request setup error: ' + error.message);
}
}
}
Retry Logic
Retry with Exponential Backoff
JavaScript:
async function apiRequestWithRetry(endpoint, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
return await apiClient.get(endpoint);
} catch (error) {
if (i === maxRetries - 1) throw error;
// Exponential backoff
const delay = Math.pow(2, i) * 1000;
await new Promise(resolve => setTimeout(resolve, delay));
}
}
}
Complete Example: E-commerce Integration
JavaScript:
class O2VendStore {
constructor(apiKey, baseUrl) {
this.apiClient = axios.create({
baseURL: baseUrl,
headers: {
'X-O2VEND-SHOPFRONT-API-KEY': apiKey,
'Content-Type': 'application/json'
}
});
}
async getProducts(filters = {}) {
const response = await this.apiClient.post('/products', {
page: 1,
pageSize: 20,
filters
});
return response.data;
}
async getProduct(productId) {
const response = await this.apiClient.get(`/products/${productId}`);
return response.data;
}
async addToCart(productId, variantId, quantity) {
const response = await this.apiClient.post('/cart/items', {
productId,
variantId,
quantity
});
return response.data;
}
async getCart() {
const response = await this.apiClient.get('/cart');
return response.data;
}
async search(query) {
const response = await this.apiClient.post('/search', {
query,
page: 1,
pageSize: 20
});
return response.data;
}
}
// Usage
const store = new O2VendStore(
'your-api-key',
'https://your-store.o2vend.com/shopfront/api/v2'
);
// Get products
const products = await store.getProducts({ available: true });
// Add to cart
await store.addToCart('prod-123', 'var-456', 1);
// Get cart
const cart = await store.getCart();
Next Steps
- Authentication - Learn authentication
- Endpoints - Complete endpoint reference
- Overview - API overview