The Ona SDK enables seamless integration with the Ona Energy AI Platform, allowing users to:
- Upload large historical datasets for interpolation, model training, and forecasting.
- Retrieve pre-signed URLs for secure file uploads to AWS S3.
- Interact programmatically with Asobaβs APIs for energy forecasting, dispatching, and analysis.
This SDK provides support for JavaScript (Node.js & Browser) and Python, making it easy for developers to integrate Ona into third-party applications.
β Pre-Signed URL Generation β Secure and efficient file uploads to AWS S3.
β Historical Data Upload β Enable seamless ingestion of large energy datasets.
β Dual SDK Support β Use in both JavaScript and Python applications.
β Error Handling β Detailed API responses and logging for debugging.
β Future Compatibility β Support for forecasting & dispatch APIs (coming soon!)
Before installing, ensure you have:
- Node.js 14+ (for JavaScript SDK)
- Python 3.7+ (for Python SDK)
- AWS Credentials configured in
.env
- API Key for secure authentication
npm install asoba-sdk
or manually:
sh
Copy
Edit
mkdir asoba-sdk && cd asoba-sdk
npm init -y
npm install axios dotenv
pip install requests python-dotenv
or manually:
sh
Copy
Edit
mkdir asoba_sdk && cd asoba_sdk
python -m venv venv && source venv/bin/activate
pip install requests python-dotenv
Create a .env file with:
ASOBA_API_URL=https://yn058ezh38.execute-api.af-south-1.amazonaws.com/test
ASOBA_API_KEY=your-api-key-here
require("dotenv").config();
const axios = require("axios");
const fs = require("fs");
class AsobaUploader {
constructor() {
this.apiUrl = process.env.ASOBA_API_URL;
this.apiKey = process.env.ASOBA_API_KEY;
if (!this.apiUrl || !this.apiKey) {
throw new Error("Missing API URL or API Key. Set ASOBA_API_URL and ASOBA_API_KEY in .env.");
}
}
async getPresignedUrl(customer_id, region, location, manufacturer, filename) {
const url = `${this.apiUrl}/upload_train`;
const headers = { "x-api-key": this.apiKey };
try {
const response = await axios.get(url, {
params: { customer_id, region, location, manufacturer, filename },
headers,
});
return response.data;
} catch (error) {
console.error("Error fetching pre-signed URL:", error);
throw error;
}
}
async uploadFile(filePath, presignedUrl) {
try {
const fileData = fs.readFileSync(filePath);
await axios.put(presignedUrl, fileData, { headers: { "Content-Type": "text/csv" } });
console.log("File uploaded successfully!");
} catch (error) {
console.error("Error uploading file:", error);
throw error;
}
}
async uploadToS3(filePath, customer_id, region, location, manufacturer) {
const filename = filePath.split("/").pop();
console.log("Fetching Pre-Signed URL...");
const { presigned_url } = await this.getPresignedUrl(customer_id, region, location, manufacturer, filename);
console.log("Uploading to S3...");
await this.uploadFile(filePath, presigned_url);
console.log(`Upload completed: ${presigned_url}`);
}
}
// Example Usage
(async () => {
const uploader = new AsobaUploader();
await uploader.uploadToS3("sample.csv", "280001", "af-south-1", "CapeTown", "lux");
})();
import os
import requests
import datetime
class OnaUploader:
def __init__(self):
"""Initialize SDK with API URL and API Key from environment variables."""
self.api_upload_url = os.getenv("ONA_API_UPLOAD_URL")
self.api_train_url = os.getenv("ONA_API_UPLOAD_URL")
self.api_key = os.getenv("ONA_API_KEY")
def get_presigned_url(self, customer_id, region, location, manufacturer, filename):
"""Step 1: Request a pre-signed URL from the Ona API."""
params = {
"customer_id": customer_id,
"region": region,
"location": location,
"manufacturer": manufacturer,
"filename": filename,
}
url = f"{self.api_upload_url}/upload_train"
headers = {"x-api-key": self.api_key, "Content-Type": "application/json"}
print(url)
print(f"Headers being sent: {headers}") #Print the headers being sent
try:
response = requests.post(url, params=params, headers=headers)
response.raise_for_status()
temp = response.json()
return temp
except requests.exceptions.RequestException as e:
print(f"Error fetching pre-signed URL: {e}")
raise
def upload_file(self, file_path, presigned_url):
"""Step 2: Upload a file to S3 using the pre-signed URL."""
try:
with open(file_path, "rb") as file:
headers = {"Content-Type": "text/csv"} # Enforce correct MIME type
response = requests.put(presigned_url, data=file, headers=headers)
response.raise_for_status()
print("File uploaded successfully!")
except requests.exceptions.RequestException as e:
print(f"Error uploading file to S3: {e}")
raise
def upload_file_to_s3(self, file_path, customer_id, region, location, manufacturer):
"""Combined function: Requests a pre-signed URL and uploads a file."""
filename = os.path.basename(file_path)
timestamp = datetime.datetime.now().strftime("%Y%m%d%H%M%S") # Get current timestamp
new_filename = f"{timestamp}_{filename}" # Create new filename with timestamp
try:
print("Requesting pre-signed URL...")
presigned_data = self.get_presigned_url(customer_id, region, location, manufacturer, new_filename)
presigned_url = presigned_data.get("presigned_url")
if not presigned_url:
raise ValueError("No presigned URL returned from API.")
print("Uploading file to S3...")
self.upload_file(file_path, presigned_url)
return presigned_url
except Exception as e:
print(f"Error in file upload process: {e}")
raise
def train_forecaster(self, customer_id, region, location, manufacturer, serial_number, testing):
"""Step 1: Request a pre-signed URL from the Ona API."""
params = {
"customer_id": customer_id,
"location": location,
"manufacturer": manufacturer,
"region": region,
"serial_number": serial_number,
"testing": testing
}
url = f"{self.api_train_url}/upload_train"
headers = {"x-api-key": self.api_key, "Content-Type": "application/json"}
print(url)
print(f"Headers being sent: {headers}") #Print the headers being sent
try:
response = requests.post(url, params=params, headers=headers)
response.raise_for_status()
temp = response.json()
return temp
except requests.exceptions.RequestException as e:
print(f"Error training model: {e}")
raise
# Example Usage
if __name__ == "__main__":
uploader = AsobaUploader();
uploader.upload_to_s3("sample.csv", "280001", "af-south-1", "CapeTown", "lux")
πΉ getPresignedUrl(customer_id, region, location, manufacturer, filename)
Returns: A pre-signed S3 URL to upload historical energy data.
Usage:
- JavaScript:
uploader.getPresignedUrl("280001", "af-south-1", "CapeTown", "lux", "data.csv")
- Python:
uploader.get_presigned_url("280001", "af-south-1", "CapeTown", "lux", "data.csv")
πΉ uploadFile(filePath, presignedUrl)
Uploads a file to the S3 bucket using the generated pre-signed URL.
Usage:
- JavaScript:
uploader.uploadFile("sample.csv", presigned_url)
- Python:
uploader.upload_file("sample.csv", presigned_url)
πΉ uploadToS3(filePath, customer_id, region, location, manufacturer)
Fetches a pre-signed URL and uploads a file to S3 in one step.
Usage:
- JavaScript:
uploader.uploadToS3("sample.csv", "280001", "af-south-1", "CapeTown", "lux")
- Python:
uploader.upload_to_s3("sample.csv", "280001", "af-south-1", "CapeTown", "lux")
πΉ train_forecaster(self, customer_id, region, location, manufacturer, serial_number, testing)
Fetches a pre-signed URL and uploads a file to S3 in one step.
Usage:
- JavaScript:
uploader.train_forecaster(customer_id = "Reyn-Lux", region = "af-south-1", location = "CapeTown", manufacturer = "lux", serial_number = "2303053195-2443053096", testing = "True")
- Python:
uploader.train_forecaster(customer_id = "Reyn-Lux", region = "af-south-1", location = "CapeTown", manufacturer = "lux", serial_number = "2303053195-2443053096", testing = "True")
403 Forbidden
? Ensure your API key is valid.
SignatureDoesNotMatch
? Verify your .env settings.
Connection Timeout
? Check your internet connection and retry.
π Model Training & Forecasting API Integration
π Data Synchronization for Real-Time Dispatch
π Webhooks for Asynchronous Processing
For support, reach out to [email protected]