# API Examples
This page provides code examples for interacting with the NETTS API in various programming languages.
# Python Examples
# Fetching Energy Prices
#!/usr/bin/env python3
import sys
import json
import requests
from datetime import datetime
# Configuration
url = "https://netts.io/apiv2/prices"
api_key = "your_api_key" # Replace with your actual API key
headers = {
"Content-Type": "application/json",
"X-API-KEY": api_key
}
try:
print(f"[{datetime.now()}] Sending price request to {url}")
# Send GET request to the prices API
response = requests.get(url, headers=headers, timeout=15)
# Process JSON response
if response.status_code == 200:
data = response.json()
# Print summary information
print("\nPrice information:")
print(f"Status: {data.get('status')}")
print(f"Current UTC time: {data.get('current_utc_time')}")
print(f"Active period: {data.get('active_period')}")
print(f"Host price: {data.get('host_price')} TRX")
# Print information about periods
print("\nPrice periods:")
for period in data.get('periods', []):
is_active = period.get('is_active', False)
active_marker = " *ACTIVE*" if is_active else ""
print(f"\n{period.get('label')}{active_marker}:")
print(f" Time: {period.get('period')}")
prices = period.get('prices', {})
# Less than 200k energy
less_than_200k = prices.get('less_than_200k', {})
print(f" Less than 200k: {less_than_200k.get('price_sun')} sun")
# Exactly 131k energy
equal_131k = prices.get('equal_131k', {})
print(f" Equal 131k: {equal_131k.get('price_sun')} sun")
# More than 200k energy
more_than_200k = prices.get('more_than_200k', {})
print(f" More than 200k: {more_than_200k.get('price_sun')} sun")
else:
print(f"Error: {response.status_code}")
print(response.text)
except requests.exceptions.RequestException as e:
print(f"Request error: {str(e)}")
except Exception as e:
print(f"Unexpected error: {str(e)}")
# Getting User Information
#!/usr/bin/env python3
import sys
import json
import requests
from datetime import datetime
# Configuration
url = "https://netts.io/apiv2/userinfo"
api_key = "your_api_key" # Replace with your actual API key
headers = {
"Content-Type": "application/json",
"X-API-KEY": api_key
}
try:
print(f"[{datetime.now()}] Requesting user information from {url}")
# Send GET request to the userinfo API
response = requests.get(url, headers=headers, timeout=15)
# Process JSON response
if response.status_code == 200:
data = response.json()
# Print user information
print("\nUser information:")
print(f"Status: {data.get('status')}")
print(f"Timestamp: {data.get('timestamp')}")
print(f"User ID: {data.get('user_id')}")
user_info = data.get('user_info', {})
print(f"Email: {user_info.get('email', 'N/A')}")
print(f"Name: {user_info.get('name', 'N/A')}")
# Print statistics
stats = data.get('stats', {})
print("\nUser statistics:")
print(f"Balance: {stats.get('balance', 0)} TRX")
print(f"Total Delegations: {stats.get('total_delegations', 0)}")
print(f"Total Energy Delegated: {stats.get('total_energy_delegated', 0)}")
print(f"Total TRX Spent: {stats.get('total_trx_spent', 0)} TRX")
print(f"Total Deposit: {stats.get('total_deposit', 0)} TRX")
print(f"Avg. Rate (Sun/Energy): {stats.get('avg_rate_sun_energy', 0)}")
print(f"Save by Netts: {stats.get('save_by_netts_percent', 0)}%")
print(f"Save in dollars: ${stats.get('save_in_dollars', 0)}")
# Print network information
network_info = data.get('network_info', {})
print("\nNetwork information:")
print(f"TRX Price: ${network_info.get('trx_price', 0)}")
print(f"Network Energy Fee: {network_info.get('network_energy_fee', 0)}")
else:
print(f"Error: {response.status_code}")
print(response.text)
except requests.exceptions.RequestException as e:
print(f"Request error: {str(e)}")
except Exception as e:
print(f"Unexpected error: {str(e)}")
# JavaScript Examples
# Fetching Energy Prices
// Using fetch API (modern browsers and Node.js with node-fetch)
const fetchPrices = async () => {
const url = 'https://netts.io/apiv2/prices';
const apiKey = 'your_api_key'; // Replace with your actual API key
try {
const response = await fetch(url, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'X-API-KEY': apiKey
}
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
// Display summary information
console.log('Price information:');
console.log(`Status: ${data.status}`);
console.log(`Current UTC time: ${data.current_utc_time}`);
console.log(`Active period: ${data.active_period}`);
console.log(`Host price: ${data.host_price} TRX`);
// Display periods information
console.log('\nPrice periods:');
data.periods.forEach(period => {
const activeMarker = period.is_active ? ' *ACTIVE*' : '';
console.log(`\n${period.label}${activeMarker}:`);
console.log(` Time: ${period.period}`);
// Display prices for different energy amounts
console.log(` Less than 200k: ${period.prices.less_than_200k.price_sun} sun`);
console.log(` Equal 131k: ${period.prices.equal_131k.price_sun} sun`);
console.log(` More than 200k: ${period.prices.more_than_200k.price_sun} sun`);
});
return data;
} catch (error) {
console.error('Error fetching prices:', error);
throw error;
}
};
// Call the function
fetchPrices().catch(console.error);
# Getting User Information
// Using fetch API (modern browsers and Node.js with node-fetch)
const fetchUserInfo = async () => {
const url = 'https://netts.io/apiv2/userinfo';
const apiKey = 'your_api_key'; // Replace with your actual API key
try {
const response = await fetch(url, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'X-API-KEY': apiKey
}
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
// Display user information
console.log('User information:');
console.log(`Status: ${data.status}`);
console.log(`Timestamp: ${data.timestamp}`);
console.log(`User ID: ${data.user_id}`);
console.log(`Email: ${data.user_info.email || 'N/A'}`);
console.log(`Name: ${data.user_info.name || 'N/A'}`);
// Display statistics
console.log('\nUser statistics:');
console.log(`Balance: ${data.stats.balance} TRX`);
console.log(`Total Delegations: ${data.stats.total_delegations}`);
console.log(`Total Energy Delegated: ${data.stats.total_energy_delegated}`);
console.log(`Total TRX Spent: ${data.stats.total_trx_spent} TRX`);
console.log(`Total Deposit: ${data.stats.total_deposit} TRX`);
console.log(`Avg. Rate (Sun/Energy): ${data.stats.avg_rate_sun_energy}`);
console.log(`Save by Netts: ${data.stats.save_by_netts_percent}%`);
console.log(`Save in dollars: $${data.stats.save_in_dollars}`);
// Display network information
console.log('\nNetwork information:');
console.log(`TRX Price: $${data.network_info.trx_price}`);
console.log(`Network Energy Fee: ${data.network_info.network_energy_fee}`);
return data;
} catch (error) {
console.error('Error fetching user info:', error);
throw error;
}
};
// Call the function
fetchUserInfo().catch(console.error);
# PHP Examples
# Fetching Energy Prices
<?php
// Configuration
$url = "https://netts.io/apiv2/prices";
$apiKey = "your_api_key"; // Replace with your actual API key
// Set up cURL
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
"X-API-KEY: $apiKey"
]);
// Execute the request
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
// Check for errors
if ($httpCode != 200) {
echo "Error: HTTP Code $httpCode\n";
echo $response;
exit(1);
}
// Process the response
$data = json_decode($response, true);
// Display summary information
echo "Price information:\n";
echo "Status: " . $data['status'] . "\n";
echo "Current UTC time: " . $data['current_utc_time'] . "\n";
echo "Active period: " . $data['active_period'] . "\n";
echo "Host price: " . $data['host_price'] . " TRX\n";
// Display periods information
echo "\nPrice periods:\n";
foreach ($data['periods'] as $period) {
$activeMarker = $period['is_active'] ? ' *ACTIVE*' : '';
echo "\n" . $period['label'] . $activeMarker . ":\n";
echo " Time: " . $period['period'] . "\n";
// Display prices for different energy amounts
echo " Less than 200k: " . $period['prices']['less_than_200k']['price_sun'] . " sun\n";
echo " Equal 131k: " . $period['prices']['equal_131k']['price_sun'] . " sun\n";
echo " More than 200k: " . $period['prices']['more_than_200k']['price_sun'] . " sun\n";
}
?>
# Getting User Information
<?php
// Configuration
$url = "https://netts.io/apiv2/userinfo";
$apiKey = "your_api_key"; // Replace with your actual API key
// Set up cURL
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
"X-API-KEY: $apiKey"
]);
// Execute the request
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
// Check for errors
if ($httpCode != 200) {
echo "Error: HTTP Code $httpCode\n";
echo $response;
exit(1);
}
// Process the response
$data = json_decode($response, true);
// Display user information
echo "User information:\n";
echo "Status: " . $data['status'] . "\n";
echo "Timestamp: " . $data['timestamp'] . "\n";
echo "User ID: " . $data['user_id'] . "\n";
echo "Email: " . ($data['user_info']['email'] ?? 'N/A') . "\n";
echo "Name: " . ($data['user_info']['name'] ?? 'N/A') . "\n";
// Display statistics
echo "\nUser statistics:\n";
echo "Balance: " . $data['stats']['balance'] . " TRX\n";
echo "Total Delegations: " . $data['stats']['total_delegations'] . "\n";
echo "Total Energy Delegated: " . $data['stats']['total_energy_delegated'] . "\n";
echo "Total TRX Spent: " . $data['stats']['total_trx_spent'] . " TRX\n";
echo "Total Deposit: " . $data['stats']['total_deposit'] . " TRX\n";
echo "Avg. Rate (Sun/Energy): " . $data['stats']['avg_rate_sun_energy'] . "\n";
echo "Save by Netts: " . $data['stats']['save_by_netts_percent'] . "%\n";
echo "Save in dollars: $" . $data['stats']['save_in_dollars'] . "\n";
// Display network information
echo "\nNetwork information:\n";
echo "TRX Price: $" . $data['network_info']['trx_price'] . "\n";
echo "Network Energy Fee: " . $data['network_info']['network_energy_fee'] . "\n";
?>
# Error Handling
All examples should implement proper error handling. Here's an extended Python example that demonstrates how to handle various error scenarios:
#!/usr/bin/env python3
import sys
import json
import requests
from datetime import datetime
# Configuration
url = "https://netts.io/apiv2/prices"
api_key = "your_api_key" # Replace with your actual API key
headers = {
"Content-Type": "application/json",
"X-API-KEY": api_key
}
try:
print(f"[{datetime.now()}] Sending price request to {url}")
# Send GET request to the prices API
response = requests.get(url, headers=headers, timeout=15)
# Check for HTTP errors
if response.status_code != 200:
if response.status_code == 401:
print("Authentication error: Invalid API key or IP not in whitelist")
elif response.status_code == 429:
print("Rate limit exceeded: Too many requests")
elif response.status_code >= 500:
print("Server error: The API server encountered an error")
else:
print(f"HTTP Error: {response.status_code}")
# Try to parse error message from JSON response
try:
error_data = response.json()
print(f"Error message: {error_data.get('msg', 'Unknown error')}")
except:
print(f"Raw response: {response.text}")
sys.exit(1)
# Process JSON response
try:
data = response.json()
# Check status in response
if data.get('status') != 'success':
print(f"API returned non-success status: {data.get('status')}")
print(f"Error message: {data.get('message', 'No message provided')}")
sys.exit(1)
# Continue processing the successful response...
print("\nPrice information:")
print(f"Current UTC time: {data.get('current_utc_time')}")
print(f"Active period: {data.get('active_period')}")
# ... rest of the processing code
except json.JSONDecodeError:
print("Error: Could not parse JSON response")
print(f"Raw response: {response.text}")
sys.exit(1)
except requests.exceptions.Timeout:
print("Error: Request timed out")
sys.exit(1)
except requests.exceptions.ConnectionError:
print("Error: Could not connect to the API server")
sys.exit(1)
except requests.exceptions.RequestException as e:
print(f"Request error: {str(e)}")
sys.exit(1)
except Exception as e:
print(f"Unexpected error: {str(e)}")
sys.exit(1)