Node.js Example for Calling API
Node.js Example for Calling the CatFee.IO REST API
Prerequisites
npm install axiosExample Code
const axios = require('axios');
const crypto = require('crypto');
const API_KEY = 'your_api_key'; // Replace with your actual API Key
const API_SECRET = 'your_api_secret'; // Replace with your actual API Secret
const BASE_URL = 'https://api.catfee.io';
// Generate the current timestamp in ISO 8601 format
function generateTimestamp() {
return new Date().toISOString();
}
// Build request path including query parameters
function buildRequestPath(path, queryParams) {
if (!queryParams || Object.keys(queryParams).length === 0) {
return path;
}
const queryString = new URLSearchParams(queryParams).toString();
return `${path}?${queryString}`;
}
// Generate signature using HMAC-SHA256
function generateSignature(timestamp, method, requestPath) {
const signString = timestamp + method + requestPath;
return crypto.createHmac('sha256', API_SECRET)
.update(signString)
.digest('base64');
}
// Create and send HTTP request
async function createRequest(url, method, timestamp, signature) {
const headers = {
'Content-Type': 'application/json',
'CF-ACCESS-KEY': API_KEY,
'CF-ACCESS-SIGN': signature,
'CF-ACCESS-TIMESTAMP': timestamp
};
try {
const response = await axios({
url,
method,
headers,
});
return response.data;
} catch (error) {
console.error('Error: ', error.response ? error.response.data : error.message);
throw error;
}
}
async function main() {
const method = 'POST'; // Can be changed to "GET", "PUT", "DELETE"
const path = '/v1/order';
// Example: Create an order
const queryParams = {
quantity: '65000',
receiver: 'TRON_ADDRESS',
duration: '1h'
};
// Generate timestamp, request path, and signature
const timestamp = generateTimestamp();
const requestPath = buildRequestPath(path, queryParams);
const signature = generateSignature(timestamp, method, requestPath);
// Compose full request URL
const url = BASE_URL + requestPath;
// Send request
try {
const response = await createRequest(url, method, timestamp, signature);
console.log('Response Data: ', response);
} catch (error) {
console.error('Request failed', error);
}
}
// Run the main function
main();Code Explanation
Notes
Summary
Last updated