Complete examples for integrating with TrustScan API.
No setup needed! Just use the commands below.
// Example using fetch API
const API_BASE_URL = "http://localhost:5000/api";
let authToken = "";
// Helper function
async function apiCall(endpoint, options = {}) {
const response = await fetch(`${API_BASE_URL}${endpoint}`, {
...options,
headers: {
"Content-Type": "application/json",
...(authToken && { Authorization: `Bearer ${authToken}` }),
...options.headers,
},
});
const data = await response.json();
if (!response.ok) {
throw new Error(data.message || "API request failed");
}
return data;
}import requests
API_BASE_URL = 'http://localhost:5000/api'
auth_token = ''
def api_call(endpoint, method='GET', data=None):
headers = {
'Content-Type': 'application/json',
}
if auth_token:
headers['Authorization'] = f'Bearer {auth_token}'
response = requests.request(
method,
f'{API_BASE_URL}{endpoint}',
json=data,
headers=headers
)
response.raise_for_status()
return response.json()cURL:
curl -X POST http://localhost:5000/api/auth/register \
-H "Content-Type: application/json" \
-d '{
"name": "John Doe",
"email": "john@example.com",
"password": "password123",
"company": "Acme Corp"
}'JavaScript:
const registerUser = async () => {
try {
const data = await apiCall("/auth/register", {
method: "POST",
body: JSON.stringify({
name: "John Doe",
email: "john@example.com",
password: "password123",
company: "Acme Corp",
}),
});
authToken = data.data.token;
console.log("Registered successfully:", data.data.user);
return data;
} catch (error) {
console.error("Registration failed:", error);
}
};Python:
def register_user():
global auth_token
try:
data = api_call('/auth/register', method='POST', data={
'name': 'John Doe',
'email': 'john@example.com',
'password': 'password123',
'company': 'Acme Corp'
})
auth_token = data['data']['token']
print('Registered successfully:', data['data']['user'])
return data
except Exception as e:
print('Registration failed:', e)cURL:
curl -X POST http://localhost:5000/api/auth/login \
-H "Content-Type: application/json" \
-d '{
"email": "admin@trustscan.com",
"password": "Admin@123456"
}'JavaScript:
const login = async (email, password) => {
const data = await apiCall("/auth/login", {
method: "POST",
body: JSON.stringify({ email, password }),
});
authToken = data.data.token;
return data.data.user;
};
// Usage
const user = await login("admin@trustscan.com", "Admin@123456");Python:
def login(email, password):
global auth_token
data = api_call('/auth/login', method='POST', data={
'email': email,
'password': password
})
auth_token = data['data']['token']
return data['data']['user']
# Usage
user = login('admin@trustscan.com', 'Admin@123456')cURL:
curl http://localhost:5000/api/auth/me \
-H "Authorization: Bearer YOUR_TOKEN"JavaScript:
const getProfile = async () => {
return await apiCall("/auth/me");
};cURL:
curl -X POST http://localhost:5000/api/users/manufacturer \
-H "Authorization: Bearer ADMIN_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"name": "Tech Manufacturing Co",
"email": "manufacturer@techco.com",
"password": "secure123",
"company": "Tech Manufacturing Co",
"phone": "+1234567890"
}'JavaScript:
const createManufacturer = async (manufacturerData) => {
return await apiCall("/users/manufacturer", {
method: "POST",
body: JSON.stringify(manufacturerData),
});
};
// Usage
const manufacturer = await createManufacturer({
name: "Tech Manufacturing Co",
email: "manufacturer@techco.com",
password: "secure123",
company: "Tech Manufacturing Co",
phone: "+1234567890",
});cURL:
curl "http://localhost:5000/api/users?page=1&limit=10&role=manufacturer" \
-H "Authorization: Bearer ADMIN_TOKEN"JavaScript:
const getUsers = async (filters = {}) => {
const params = new URLSearchParams(filters);
return await apiCall(`/users?${params}`);
};
// Usage
const users = await getUsers({
page: 1,
limit: 10,
role: "manufacturer",
});cURL:
curl -X POST http://localhost:5000/api/products \
-H "Authorization: Bearer MANUFACTURER_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"name": "Premium Smartphone X1",
"description": "Latest flagship smartphone with advanced features",
"sku": "PHONE-X1-2024",
"category": "Electronics",
"price": 999.99,
"weight": 0.2,
"batchNumber": "BATCH-2024-001"
}'JavaScript:
const createProduct = async (productData) => {
return await apiCall("/products", {
method: "POST",
body: JSON.stringify(productData),
});
};
// Usage
const product = await createProduct({
name: "Premium Smartphone X1",
description: "Latest flagship smartphone with advanced features",
sku: "PHONE-X1-2024",
category: "Electronics",
price: 999.99,
weight: 0.2,
batchNumber: "BATCH-2024-001",
});
console.log("Product created with QR code:", product.data.product.qrCode);
console.log("QR code image:", product.data.qrCodeImage); // Base64 imagePython:
def create_product(product_data):
return api_call('/products', method='POST', data=product_data)
# Usage
product = create_product({
'name': 'Premium Smartphone X1',
'description': 'Latest flagship smartphone',
'sku': 'PHONE-X1-2024',
'category': 'Electronics',
'price': 999.99
})
print('QR Code:', product['data']['product']['qrCode'])cURL:
curl "http://localhost:5000/api/products?category=Electronics&status=manufactured&page=1&limit=10" \
-H "Authorization: Bearer TOKEN"JavaScript:
const getProducts = async (filters = {}) => {
const params = new URLSearchParams(filters);
return await apiCall(`/products?${params}`);
};
// Usage
const products = await getProducts({
category: "Electronics",
status: "manufactured",
page: 1,
limit: 10,
search: "smartphone",
});cURL:
curl http://localhost:5000/api/products/qr/TS-1234567890-uuidJavaScript:
const getProductByQR = async (qrCode) => {
return await apiCall(`/products/qr/${qrCode}`);
};
// Usage
const product = await getProductByQR("TS-1234567890-uuid");cURL:
curl -X POST http://localhost:5000/api/products/PRODUCT_ID/transfer \
-H "Authorization: Bearer TOKEN" \
-H "Content-Type: application/json" \
-d '{
"newOwnerId": "USER_ID_HERE",
"location": "Distribution Center, New York",
"notes": "Transfer to regional distributor"
}'JavaScript:
const transferProduct = async (productId, transferData) => {
return await apiCall(`/products/${productId}/transfer`, {
method: "POST",
body: JSON.stringify(transferData),
});
};
// Usage
const result = await transferProduct("product_id", {
newOwnerId: "new_owner_id",
location: "Distribution Center, New York",
notes: "Transfer to regional distributor",
});cURL:
curl http://localhost:5000/api/products/PRODUCT_ID/history \
-H "Authorization: Bearer TOKEN"JavaScript:
const getProductHistory = async (productId) => {
return await apiCall(`/products/${productId}/history`);
};
// Usage
const history = await getProductHistory("product_id");
console.log("Ownership transfers:", history.data.ownershipHistory);cURL:
curl -X POST http://localhost:5000/api/scans \
-H "Authorization: Bearer TOKEN" \
-H "Content-Type: application/json" \
-d '{
"qrCode": "TS-1234567890-uuid",
"location": {
"latitude": 40.7128,
"longitude": -74.0060,
"address": "New York, NY"
},
"deviceInfo": {
"platform": "iOS"
},
"notes": "Scanned at retail store"
}'JavaScript:
const scanProduct = async (qrCode, locationData = null) => {
return await apiCall("/scans", {
method: "POST",
body: JSON.stringify({
qrCode,
location: locationData,
deviceInfo: {
platform: navigator.platform,
},
}),
});
};
// Usage
const scanResult = await scanProduct("TS-1234567890-uuid", {
latitude: 40.7128,
longitude: -74.006,
address: "New York, NY",
});
console.log("Product:", scanResult.data.product);
console.log("Is Authentic:", scanResult.data.scan.isAuthentic);Python:
def scan_product(qr_code, location=None):
data = {
'qrCode': qr_code,
'deviceInfo': {'platform': 'Python'}
}
if location:
data['location'] = location
return api_call('/scans', method='POST', data=data)
# Usage
scan = scan_product('TS-1234567890-uuid', {
'latitude': 40.7128,
'longitude': -74.0060,
'address': 'New York, NY'
})cURL:
curl "http://localhost:5000/api/scans?page=1&limit=10" \
-H "Authorization: Bearer TOKEN"JavaScript:
const getScanHistory = async (page = 1, limit = 10) => {
return await apiCall(`/scans?page=${page}&limit=${limit}`);
};
// Usage
const history = await getScanHistory(1, 10);cURL:
curl http://localhost:5000/api/scans/stats \
-H "Authorization: Bearer TOKEN"JavaScript:
const getScanStats = async () => {
return await apiCall("/scans/stats");
};
// Usage
const stats = await getScanStats();
console.log("Total scans:", stats.data.statistics.totalScans);
console.log("Unique products:", stats.data.statistics.uniqueProductsCount);All errors return this format:
{
"success": false,
"message": "Error description",
"errors": [
{
"field": "email",
"message": "Invalid email address"
}
]
}const handleApiCall = async (apiFunction) => {
try {
const result = await apiFunction();
return { success: true, data: result };
} catch (error) {
if (error.response) {
// API returned error
const errorData = await error.response.json();
console.error("API Error:", errorData.message);
if (errorData.errors) {
errorData.errors.forEach((err) => {
console.error(` ${err.field}: ${err.message}`);
});
}
} else {
// Network or other error
console.error("Network Error:", error.message);
}
return { success: false, error: error.message };
}
};
// Usage
const result = await handleApiCall(() => createProduct(productData));
if (result.success) {
console.log("Product created:", result.data);
} else {
console.log("Failed to create product");
}def safe_api_call(func, *args, **kwargs):
try:
result = func(*args, **kwargs)
return {'success': True, 'data': result}
except requests.exceptions.HTTPError as e:
error_data = e.response.json()
print(f"API Error: {error_data['message']}")
if 'errors' in error_data:
for err in error_data['errors']:
print(f" {err['field']}: {err['message']}")
return {'success': False, 'error': error_data['message']}
except Exception as e:
print(f"Error: {str(e)}")
return {'success': False, 'error': str(e)}
# Usage
result = safe_api_call(create_product, product_data)
if result['success']:
print('Product created:', result['data'])// 1. Admin creates manufacturer
await login("admin@trustscan.com", "Admin@123456");
const manufacturer = await createManufacturer({
name: "Electronics Inc",
email: "mfg@electronics.com",
password: "secure123",
company: "Electronics Inc",
});
// 2. Manufacturer logs in and creates product
await login("mfg@electronics.com", "secure123");
const product = await createProduct({
name: "Smart Watch Pro",
description: "Advanced fitness tracker",
sku: "SW-PRO-2024",
category: "Wearables",
price: 299.99,
});
console.log("QR Code:", product.data.product.qrCode);
// 3. Get supplier and transfer product
const suppliers = await apiCall("/users/suppliers");
const supplier = suppliers.data[0];
await transferProduct(product.data.product._id, {
newOwnerId: supplier._id,
location: "Warehouse A",
notes: "Initial shipment",
});
// 4. User scans product
await login("user@example.com", "password");
const scan = await scanProduct(product.data.product.qrCode, {
latitude: 40.7128,
longitude: -74.006,
});
console.log("Product verified:", scan.data.product.name);
// 5. View complete history
const history = await getProductHistory(product.data.product._id);
console.log("Product journey:", history.data.ownershipHistory);- Always store tokens securely - Never expose them in logs or client-side code
- Handle token expiry - Implement refresh logic or re-authentication
- Use environment variables - Store API URL and credentials safely
- Implement retry logic - For network failures
- Cache frequently accessed data - Like manufacturer/supplier lists
- Validate before sending - Check data format before API calls
- Log errors properly - For debugging and monitoring