Code Examples
Production-ready examples for integrating GlobalSIM into your applications.
Complete Python Application
import requests
import time
from datetime import datetime, timedelta
from typing import List, Dict, Optional
API_KEY = 'YOUR_API_KEY'
API_URL = 'https://api.wayscloud.services/v1/globalsim'
class GlobalSIMManager:
def __init__(self, api_key: str):
self.api_key = api_key
self.headers = {
'Authorization': f'Bearer {api_key}',
'Content-Type': 'application/json'
}
def list_sims(self, status: Optional[str] = None) -> Dict:
"""List all SIM cards with optional status filter"""
params = {}
if status:
params['status'] = status
response = requests.get(
f'{API_URL}/sims',
headers=self.headers,
params=params
)
response.raise_for_status()
return response.json()
def get_sim_details(self, iccid: str) -> Dict:
"""Get detailed information for a specific SIM"""
response = requests.get(
f'{API_URL}/sims/{iccid}',
headers=self.headers
)
response.raise_for_status()
return response.json()
def get_sim_sessions(self, iccid: str, days: int = 7) -> Dict:
"""Get connectivity sessions for a SIM"""
end_date = datetime.now().date()
start_date = end_date - timedelta(days=days)
params = {
'start_date': start_date.isoformat(),
'end_date': end_date.isoformat()
}
response = requests.get(
f'{API_URL}/sims/{iccid}/sessions',
headers=self.headers,
params=params
)
response.raise_for_status()
return response.json()
def get_billing(self, start_date: Optional[str] = None,
end_date: Optional[str] = None) -> Dict:
"""Get billing information"""
params = {}
if start_date:
params['start_date'] = start_date
if end_date:
params['end_date'] = end_date
response = requests.get(
f'{API_URL}/sims/billing',
headers=self.headers,
params=params
)
response.raise_for_status()
return response.json()
def order_sims(self, quantity: int) -> Dict:
"""Order new SIM cards"""
payload = {'quantity': quantity}
response = requests.post(
f'{API_URL}/sims/order',
headers=self.headers,
json=payload
)
response.raise_for_status()
return response.json()
def get_subscription(self) -> Dict:
"""Get subscription details"""
response = requests.get(
f'{API_URL}/subscription',
headers=self.headers
)
response.raise_for_status()
return response.json()
def monitor_data_usage(self, threshold_mb: float = 500) -> List[Dict]:
"""Find SIMs exceeding data usage threshold"""
billing = self.get_billing()
high_usage = [
sim for sim in billing.get('by_sim', [])
if sim.get('data_usage_mb', 0) > threshold_mb
]
return high_usage
def generate_report(self) -> Dict:
"""Generate comprehensive usage report"""
sims = self.list_sims()
billing = self.get_billing()
subscription = self.get_subscription()
return {
'generated_at': datetime.now().isoformat(),
'subscription': {
'plan': subscription.get('plan'),
'active_sims': subscription.get('usage', {}).get('active_sims'),
'max_sims': subscription.get('limits', {}).get('max_sims')
},
'billing': {
'total_cost': billing.get('summary', {}).get('total_cost'),
'subscription_fees': billing.get('summary', {}).get('subscription_fees'),
'data_costs': billing.get('summary', {}).get('data_costs'),
'currency': billing.get('summary', {}).get('currency')
},
'data_usage': {
'total_mb': billing.get('data_usage', {}).get('total_mb')
},
'top_users': sorted(
billing.get('by_sim', []),
key=lambda x: x.get('data_usage_mb', 0),
reverse=True
)[:5]
}
def print_dashboard(self):
"""Print a simple dashboard"""
report = self.generate_report()
print("=" * 50)
print("GlobalSIM Dashboard")
print("=" * 50)
print(f"\nGenerated: {report['generated_at']}")
print(f"\nSubscription:")
print(f" Plan: {report['subscription']['plan']}")
print(f" SIMs: {report['subscription']['active_sims']}/{report['subscription']['max_sims']}")
print(f"\nBilling:")
currency = report['billing']['currency']
print(f" Total: {currency} {report['billing']['total_cost']:.2f}")
print(f" Subscription: {currency} {report['billing']['subscription_fees']:.2f}")
print(f" Data: {currency} {report['billing']['data_costs']:.2f}")
print(f"\nData Usage:")
print(f" Total: {report['data_usage']['total_mb']:.2f} MB")
print(f"\nTop 5 Users:")
for i, sim in enumerate(report['top_users'], 1):
print(f" {i}. {sim['iccid']}: {sim['data_usage_mb']:.2f} MB ({currency} {sim['total_cost']:.2f})")
# Example usage
if __name__ == '__main__':
manager = GlobalSIMManager(API_KEY)
# Print dashboard
manager.print_dashboard()
# List all active SIMs
print("\n" + "=" * 50)
print("Active SIMs")
print("=" * 50)
active_sims = manager.list_sims(status='active')
for sim in active_sims.get('sims', []):
print(f"\n{sim['iccid']}")
print(f" Number: {sim.get('msisdn', 'N/A')}")
print(f" Network: {sim.get('current_network', {}).get('operator', 'N/A')}")
print(f" Data: {sim.get('data_usage_mb', 0):.2f} MB")
# Check high usage SIMs
high_usage = manager.monitor_data_usage(threshold_mb=300)
if high_usage:
print("\nHigh Usage SIMs (>300 MB):")
for sim in high_usage:
print(f" {sim['iccid']}: {sim['data_usage_mb']:.2f} MB")
Node.js Monitoring Service
const axios = require('axios');
const API_KEY = process.env.WAYSCLOUD_API_KEY;
const API_URL = 'https://api.wayscloud.services/v1/globalsim';
class GlobalSIMMonitor {
constructor(apiKey) {
this.apiKey = apiKey;
this.client = axios.create({
baseURL: API_URL,
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
}
});
}
async listSims(status = null) {
try {
const params = status ? { status } : {};
const response = await this.client.get('/sims', { params });
return response.data;
} catch (error) {
console.error('Error listing SIMs:', error.message);
throw error;
}
}
async getBilling(startDate = null, endDate = null) {
try {
const params = {};
if (startDate) params.start_date = startDate;
if (endDate) params.end_date = endDate;
const response = await this.client.get('/sims/billing', { params });
return response.data;
} catch (error) {
console.error('Error getting billing:', error.message);
throw error;
}
}
async getSimSessions(iccid, days = 7) {
try {
const endDate = new Date();
const startDate = new Date(endDate);
startDate.setDate(startDate.getDate() - days);
const params = {
start_date: startDate.toISOString().split('T')[0],
end_date: endDate.toISOString().split('T')[0]
};
const response = await this.client.get(`/sims/${iccid}/sessions`, { params });
return response.data;
} catch (error) {
console.error(`Error getting sessions for ${iccid}:`, error.message);
throw error;
}
}
async checkDataUsage(thresholdMB = 500) {
console.log(`Checking SIMs exceeding ${thresholdMB} MB...`);
const billing = await this.getBilling();
const highUsage = billing.by_sim.filter(
sim => sim.data_usage_mb > thresholdMB
);
if (highUsage.length > 0) {
console.log(`Found ${highUsage.length} SIMs exceeding threshold:`);
highUsage.forEach(sim => {
console.log(
` ${sim.iccid}: ${sim.data_usage_mb.toFixed(2)} MB ` +
`(${billing.summary.currency} ${sim.total_cost.toFixed(2)})`
);
});
} else {
console.log('All SIMs within usage threshold');
}
return highUsage;
}
async generateDailyReport() {
console.log('\n' + '='.repeat(60));
console.log('GlobalSIM Daily Report');
console.log('='.repeat(60));
console.log(`Generated: ${new Date().toISOString()}\n`);
try {
const [sims, billing] = await Promise.all([
this.listSims(),
this.getBilling()
]);
console.log('SIM Status:');
console.log(` Total SIMs: ${sims.total}`);
console.log(` Active: ${sims.sims.filter(s => s.status === 'active').length}`);
console.log('\nBilling:');
console.log(` Total Cost: ${billing.summary.currency} ${billing.summary.total_cost.toFixed(2)}`);
console.log(` Subscription: ${billing.summary.currency} ${billing.summary.subscription_fees.toFixed(2)}`);
console.log(` Data: ${billing.summary.currency} ${billing.summary.data_costs.toFixed(2)}`);
console.log('\nData Usage:');
console.log(` Total: ${billing.data_usage.total_mb.toFixed(2)} MB`);
console.log('\nTop 5 Data Users:');
const topUsers = billing.by_sim
.sort((a, b) => b.data_usage_mb - a.data_usage_mb)
.slice(0, 5);
topUsers.forEach((sim, i) => {
console.log(
` ${i + 1}. ${sim.iccid}: ${sim.data_usage_mb.toFixed(2)} MB ` +
`(${billing.summary.currency} ${sim.total_cost.toFixed(2)})`
);
});
console.log('\n' + '='.repeat(60) + '\n');
} catch (error) {
console.error('Error generating report:', error.message);
}
}
}
// Example usage
const monitor = new GlobalSIMMonitor(API_KEY);
(async () => {
await monitor.checkDataUsage(300);
await monitor.generateDailyReport();
})();
Flask API Wrapper
from flask import Flask, jsonify, request
import requests
import os
app = Flask(__name__)
GLOBALSIM_API_KEY = os.getenv('WAYSCLOUD_API_KEY')
GLOBALSIM_API_URL = 'https://api.wayscloud.services/v1/globalsim'
@app.route('/api/sims', methods=['GET'])
def list_sims():
"""List all SIM cards"""
try:
headers = {'Authorization': f'Bearer {GLOBALSIM_API_KEY}'}
status = request.args.get('status')
params = {'status': status} if status else {}
response = requests.get(
f'{GLOBALSIM_API_URL}/sims',
headers=headers,
params=params
)
return jsonify(response.json()), response.status_code
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/api/sims/<iccid>', methods=['GET'])
def get_sim(iccid):
"""Get SIM details"""
try:
headers = {'Authorization': f'Bearer {GLOBALSIM_API_KEY}'}
response = requests.get(
f'{GLOBALSIM_API_URL}/sims/{iccid}',
headers=headers
)
return jsonify(response.json()), response.status_code
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/api/billing', methods=['GET'])
def get_billing():
"""Get billing information"""
try:
headers = {'Authorization': f'Bearer {GLOBALSIM_API_KEY}'}
params = {}
if request.args.get('start_date'):
params['start_date'] = request.args.get('start_date')
if request.args.get('end_date'):
params['end_date'] = request.args.get('end_date')
response = requests.get(
f'{GLOBALSIM_API_URL}/sims/billing',
headers=headers,
params=params
)
return jsonify(response.json()), response.status_code
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/api/health', methods=['GET'])
def health_check():
"""Health check endpoint"""
return jsonify({'status': 'healthy'}), 200
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000, debug=False)
Next Steps
- SIM Management - API reference
- Sessions & Activity - Monitor connectivity
- Billing - Track costs