Skip to main content
v5.32
operator
manufacturer
Last updated on

REST API Recipes

This section provides ready-to-use code examples for interacting with the Charge Controller REST API. These examples demonstrate common tasks such as authentication, retrieving settings, and accessing dashboard data.

1. Authentication Flow

All examples follow the same authentication flow:

  1. Request a token from the /login endpoint
  2. Hash the password with the received token
  3. Send the username and hashed password to authenticate
  4. Use the returned session ID for subsequent API requests

2. Node.js Example

This Node.js example demonstrates how to authenticate and retrieve data from the app_settings and app_dashboard endpoints.

2.1. Prerequisites

  • Node.js (v14 or higher)
  • npm (comes with Node.js)

2.2. Installation

  1. Create a new directory for your project
  2. Create a package.json file:
{
"name": "charge-controller-api-client",
"version": "1.0.0",
"description": "A starter script for interacting with the Charge Controller REST API",
"main": "index.js",
"scripts": {
"start": "node index.js"
},
"dependencies": {
"axios": "^1.6.2"
},
"engines": {
"node": ">=14.0.0"
},
"private": true
}
  1. Install dependencies:
npm install
  1. Create an index.js file with the following code:
/**
* Charge Controller REST API Client
*
* This is a starter script for interacting with the Charge Controller REST API.
* It demonstrates how to authenticate and make requests to the API endpoints.
*
* Usage:
* 1. Install Node.js if not already installed
* 2. Run 'npm install axios' to install the required dependency
* 3. Update the configuration variables below with your Charge Controller details
* 4. Run the script with 'node index.js'
*
* The script will:
* - Authenticate with the Charge Controller
* - Fetch data from the app_settings and app_dashboard endpoints
* - Display the complete JSON responses
*/

const axios = require("axios");
const crypto = require("crypto");

// Configuration - Update these values with your Charge Controller details
const BASE_URL = "http://192.168.1.100"; // Replace with your Charge Controller IP or hostname
const USERNAME = "operator"; // Replace with your username
const PASSWORD = "your_password"; // Replace with your password
const API_VERSION = "v1"; // API version

/**
* Get authentication token from the server
* @returns {Promise<string>} Authentication token
*/
async function getToken() {
const url = `${BASE_URL}/${API_VERSION}/login`;
console.log(`Requesting token from: ${url}`);

try {
const response = await axios.get(url, {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
});

console.log(`Token request successful`);

if (!response.data || !response.data.token) {
throw new Error('Token not found in response');
}

return response.data.token;
} catch (error) {
console.error(`Token request failed: ${error.message}`);
throw error;
}
}

/**
* Hash password using SHA256
* @param {string} password - Plain text password
* @param {string} token - Authentication token
* @returns {string} Hashed password
*/
function hashPassword(password, token) {
return crypto.createHash('sha256').update(password + token).digest('hex');
}

/**
* Login to get session ID
* @param {string} username - Username
* @param {string} hashedPassword - Hashed password
* @returns {Promise<string>} Session ID
*/
async function login(username, hashedPassword) {
const url = `${BASE_URL}/${API_VERSION}/login`;
console.log(`Logging in as: ${username}`);

try {
const response = await axios.post(url, {
username,
password: hashedPassword
}, {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
});

console.log(`Login successful`);
console.log(`Response:`, JSON.stringify(response.data, null, 2));

if (response.data.session && response.data.session.id) {
return response.data.session.id;
} else {
throw new Error("Session ID not found in response!");
}
} catch (error) {
console.error(`Login failed: ${error.message}`);
throw error;
}
}

/**
* Request API endpoints
* @param {string} sessionId - Session ID for authentication
* @param {string} endpoint - API endpoint path
* @returns {Promise<object>} API response data
*/
async function fetchEndpoint(sessionId, endpoint) {
const url = `${BASE_URL}/${API_VERSION}${endpoint}`;
console.log(`Requesting API endpoint: ${url}`);

try {
const response = await axios.get(url, {
headers: {
'Authorization': sessionId,
'Accept': 'application/json',
'Content-Type': 'application/json'
}
});

console.log(`API request successful: ${endpoint}`);
return response.data;
} catch (error) {
console.error(`API request failed: ${endpoint}`);
console.error(`Error: ${error.message}`);
throw error;
}
}

/**
* Main function to run the API requests
*
* You can extend this function to request additional endpoints or implement
* other API operations as needed for your application.
*/
async function main() {
console.log('Starting Charge Controller REST API Client');
console.log(`Base URL: ${BASE_URL}`);
console.log(`API Version: ${API_VERSION}`);

try {
// Step 1: Get authentication token
const token = await getToken();
console.log('Token received successfully');

// Step 2: Hash password with token
const hashedPassword = hashPassword(PASSWORD, token);
console.log('Password hashed successfully');

// Step 3: Login with credentials
const sessionId = await login(USERNAME, hashedPassword);
console.log('Session established successfully');

// Step 4: Request API endpoints
console.log('\nFetching API Data');

// App Settings endpoint
console.log('\nRequesting App Settings:');
const appSettings = await fetchEndpoint(sessionId, '/app_settings');
console.log('App Settings data:');
console.log(JSON.stringify(appSettings, null, 2));

// App Dashboard endpoint
console.log('\nRequesting App Dashboard:');
const appDashboard = await fetchEndpoint(sessionId, '/app_dashboard');
console.log('App Dashboard data:');
console.log(JSON.stringify(appDashboard, null, 2));

// Settings Parameters endpoint
console.log('\nRequesting Settings Parameters:');
const settings = await fetchEndpoint(sessionId, '/settings');
console.log('Settings Parameters data:');
console.log(JSON.stringify(settings, null, 2));

// System State endpoint
console.log('\nRequesting System State:');
const systemState = await fetchEndpoint(sessionId, '/system_state');
console.log('System State data:');
console.log(JSON.stringify(systemState, null, 2));

// Logging Messages endpoint
console.log('\nRequesting Logging Messages:');
const messages = await fetchEndpoint(sessionId, '/messages');
console.log('Logging Messages data:');
console.log(JSON.stringify(messages, null, 2));

console.log('\nAPI requests completed successfully');

} catch (error) {
console.error('\nError occurred during API requests:');
console.error(error.message);
}
}

main();
  1. Run the script:
node index.js

3. Python Example

This Python example demonstrates how to authenticate and retrieve data from the app_settings and app_dashboard endpoints.

3.1. Prerequisites

  • Python 3.6 or higher
  • pip (Python package manager)

3.2. Installation

  1. Create a new directory for your project
  2. Create a requirements.txt file:
requests==2.31.0
  1. Install dependencies:
pip install -r requirements.txt
  1. Create a charge_controller_api.py file with the following code:
#!/usr/bin/env python3
"""
Charge Controller REST API Client

This is a starter script for interacting with the Charge Controller REST API.
It demonstrates how to authenticate and make requests to the API endpoints.

Usage:
1. Install Python 3.6 or higher if not already installed
2. Run 'pip install requests' to install the required dependency
3. Update the configuration variables below with your Charge Controller details
4. Run the script with 'python charge_controller_api.py'

The script will:
- Authenticate with the Charge Controller
- Fetch data from the app_settings and app_dashboard endpoints
- Display the complete JSON responses
"""

import hashlib
import json
import requests

# Configuration - Update these values with your Charge Controller details
BASE_URL = "http://192.168.1.100" # Replace with your Charge Controller IP or hostname
USERNAME = "operator" # Replace with your username
PASSWORD = "your_password" # Replace with your password
API_VERSION = "v1" # API version

def get_token():
"""Get authentication token from the server"""
url = f"{BASE_URL}/{API_VERSION}/login"
print(f"Requesting token from: {url}")

try:
response = requests.get(
url,
headers={
"Accept": "application/json",
"Content-Type": "application/json"
}
)
response.raise_for_status()

print("Token request successful")
data = response.json()

if not data or "token" not in data:
raise ValueError("Token not found in response")

return data["token"]
except Exception as e:
print(f"Token request failed: {str(e)}")
raise

def hash_password(password, token):
"""Hash password using SHA256"""
combined = password + token
return hashlib.sha256(combined.encode()).hexdigest()

def login(username, hashed_password):
"""Login to get session ID"""
url = f"{BASE_URL}/{API_VERSION}/login"
print(f"Logging in as: {username}")

try:
response = requests.post(
url,
json={
"username": username,
"password": hashed_password
},
headers={
"Accept": "application/json",
"Content-Type": "application/json"
}
)
response.raise_for_status()

print("Login successful")
data = response.json()
print(f"Response: {json.dumps(data, indent=2)}")

if "session" in data and "id" in data["session"]:
return data["session"]["id"]
else:
raise ValueError("Session ID not found in response!")
except Exception as e:
print(f"Login failed: {str(e)}")
raise

def fetch_endpoint(session_id, endpoint):
"""Request API endpoints"""
url = f"{BASE_URL}/{API_VERSION}{endpoint}"
print(f"Requesting API endpoint: {url}")

try:
response = requests.get(
url,
headers={
"Authorization": session_id,
"Accept": "application/json",
"Content-Type": "application/json"
}
)
response.raise_for_status()

print(f"API request successful: {endpoint}")
return response.json()
except Exception as e:
print(f"API request failed: {endpoint}")
print(f"Error: {str(e)}")
raise

def main():
"""Main function to run the API requests"""
print("\n==================================================")
print("Starting Charge Controller REST API Client")
print(f"Base URL: {BASE_URL}")
print(f"API Version: {API_VERSION}")
print("==================================================\n")

try:
# Step 1: Get authentication token
token = get_token()
print("Token received successfully")

# Step 2: Hash password with token
hashed_password = hash_password(PASSWORD, token)
print("Password hashed successfully")

# Step 3: Login with credentials
session_id = login(USERNAME, hashed_password)
print("Session established successfully")

# Step 4: Request API endpoints
print("\n==================================================")
print("Fetching API Data")
print("==================================================")

# App Settings endpoint
print("\nRequesting App Settings:")
app_settings = fetch_endpoint(session_id, "/app_settings")
print("App Settings data:")
print(json.dumps(app_settings, indent=2))

# App Dashboard endpoint
print("\nRequesting App Dashboard:")
app_dashboard = fetch_endpoint(session_id, "/app_dashboard")
print("App Dashboard data:")
print(json.dumps(app_dashboard, indent=2))

# Settings Parameters endpoint
print("\nRequesting Settings Parameters:")
settings = fetch_endpoint(session_id, "/settings")
print("Settings Parameters data:")
print(json.dumps(settings, indent=2))

# System State endpoint
print("\nRequesting System State:")
system_state = fetch_endpoint(session_id, "/system_state")
print("System State data:")
print(json.dumps(system_state, indent=2))

# Logging Messages endpoint
print("\nRequesting Logging Messages:")
messages = fetch_endpoint(session_id, "/messages")
print("Logging Messages data:")
print(json.dumps(messages, indent=2))

print("\n==================================================")
print("API requests completed successfully")
print("==================================================")

except Exception as e:
print("\n==================================================")
print("Error occurred during API requests:")
print(str(e))
print("==================================================")

if __name__ == "__main__":
main()
  1. Run the script:
python charge_controller_api.py

4. cURL Examples

These cURL examples demonstrate how to interact with the Charge Controller REST API from the command line.

4.1. Get Authentication Token

curl -X GET \
"http://192.168.1.100/v1/login" \
-H "Accept: application/json" \
-H "Content-Type: application/json"

4.2. Login with Credentials

First, hash your password with the token using a tool like Python:

import hashlib
password = "your_password"
token = "token_from_previous_request"
hashed = hashlib.sha256((password + token).encode()).hexdigest()
print(hashed)

Then use the hashed password to login:

curl -X POST \
"http://192.168.1.100/v1/login" \
-H "Accept: application/json" \
-H "Content-Type: application/json" \
-d '{
"username": "operator",
"password": "your_hashed_password"
}'

4.3. Get App Settings

curl -X GET \
"http://192.168.1.100/v1/app_settings" \
-H "Accept: application/json" \
-H "Content-Type: application/json" \
-H "Authorization: your_session_id"

4.4. Get App Dashboard

curl -X GET \
"http://192.168.1.100/v1/app_dashboard" \
-H "Accept: application/json" \
-H "Content-Type: application/json" \
-H "Authorization: your_session_id"

4.5. Get Settings Parameters

curl -X GET \
"http://192.168.1.100/v1/settings" \
-H "Accept: application/json" \
-H "Content-Type: application/json" \
-H "Authorization: your_session_id"

4.6. Get System State

curl -X GET \
"http://192.168.1.100/v1/system_state" \
-H "Accept: application/json" \
-H "Content-Type: application/json" \
-H "Authorization: your_session_id"

4.7. Get Logging Messages

curl -X GET \
"http://192.168.1.100/v1/messages" \
-H "Accept: application/json" \
-H "Content-Type: application/json" \
-H "Authorization: your_session_id"

5. Shell Script Example

This shell script combines the cURL commands into a complete workflow:

#!/bin/bash

# Configuration
BASE_URL="http://192.168.1.100"
USERNAME="operator"
PASSWORD="your_password"
API_VERSION="v1"

# Function to hash password using SHA-256
hash_password() {
local password=$1
local token=$2
echo -n "${password}${token}" | sha256sum | awk '{print $1}'
}

# Step 1: Get token
echo "Getting token..."
TOKEN_RESPONSE=$(curl -s -X GET \
"${BASE_URL}/${API_VERSION}/login" \
-H "Accept: application/json" \
-H "Content-Type: application/json")

TOKEN=$(echo $TOKEN_RESPONSE | grep -o '"token":"[^"]*"' | cut -d'"' -f4)
echo "Token received: $TOKEN"

# Step 2: Hash password
HASHED_PASSWORD=$(hash_password "$PASSWORD" "$TOKEN")
echo "Password hashed successfully"

# Step 3: Login
echo "Logging in..."
LOGIN_RESPONSE=$(curl -s -X POST \
"${BASE_URL}/${API_VERSION}/login" \
-H "Accept: application/json" \
-H "Content-Type: application/json" \
-d "{
\"username\": \"$USERNAME\",
\"password\": \"$HASHED_PASSWORD\"
}")

SESSION_ID=$(echo $LOGIN_RESPONSE | grep -o '"id":"[^"]*"' | cut -d'"' -f4)
echo "Session established with ID: $SESSION_ID"

# Step 4: Get app settings
echo -e "\nGetting app settings..."
APP_SETTINGS=$(curl -s -X GET \
"${BASE_URL}/${API_VERSION}/app_settings" \
-H "Accept: application/json" \
-H "Content-Type: application/json" \
-H "Authorization: $SESSION_ID")

echo "App Settings data:"
echo $APP_SETTINGS | jq '.'

# Step 5: Get app dashboard
echo -e "\nGetting app dashboard..."
APP_DASHBOARD=$(curl -s -X GET \
"${BASE_URL}/${API_VERSION}/app_dashboard" \
-H "Accept: application/json" \
-H "Content-Type: application/json" \
-H "Authorization: $SESSION_ID")

echo "App Dashboard data:"
echo $APP_DASHBOARD | jq '.'

# Step 6: Get settings parameters
echo -e "\nGetting settings parameters..."
SETTINGS=$(curl -s -X GET \
"${BASE_URL}/${API_VERSION}/settings" \
-H "Accept: application/json" \
-H "Content-Type: application/json" \
-H "Authorization: $SESSION_ID")

echo "Settings Parameters data:"
echo $SETTINGS | jq '.'

# Step 7: Get system state
echo -e "\nGetting system state..."
SYSTEM_STATE=$(curl -s -X GET \
"${BASE_URL}/${API_VERSION}/system_state" \
-H "Accept: application/json" \
-H "Content-Type: application/json" \
-H "Authorization: $SESSION_ID")

echo "System State data:"
echo $SYSTEM_STATE | jq '.'

# Step 8: Get logging messages
echo -e "\nGetting logging messages..."
MESSAGES=$(curl -s -X GET \
"${BASE_URL}/${API_VERSION}/messages" \
-H "Accept: application/json" \
-H "Content-Type: application/json" \
-H "Authorization: $SESSION_ID")

echo "Logging Messages data:"
echo $MESSAGES | jq '.'

echo -e "\nAPI requests completed successfully"

Save this as charge_controller_api.sh, make it executable with chmod +x charge_controller_api.sh, and run it:

./charge_controller_api.sh

Note: This script requires jq for JSON formatting. Install it with apt-get install jq on Debian/Ubuntu or brew install jq on macOS.

6. Next Steps

These examples provide a starting point for interacting with the Charge Controller REST API. You can extend them to:

  1. Access additional endpoints
  2. Implement error handling and retries
  3. Create a more robust application with logging and configuration
  4. Integrate with your own systems

For a complete reference of all available endpoints and their parameters, see the REST API Reference.