Authentication Examples
Table of Contents
Overview
These examples demonstrate how to authenticate with the RCAMS API, including login, and logout. Authentication is the first step in any interaction with the API and is required for all subsequent operations.
Note: The RCAMS API uses a basic authentication system.
Basic Authentication Flow
This example demonstrates the complete authentication flow, and logout.
Complete Authentication Flow (JavaScript)
// RCAMS API Authentication Example
// Helper function for making API requests
async function makeApiRequest(endpoint, params, apiCredentials) {
const { username, password } = apiCredentials;
// Create json data from params
const json = {};
for (const [key, value] of Object.entries(params)) {
json[key] = value;
}
const jsonString = JSON.stringify(json);
try {
const response = await fetch(`https://rcamsapi.spheronomics.com/api/v2/${endpoint}`, {
method: 'POST',
headers: {
'Authorization': 'Basic ' + btoa(`${username}:${password}`)
},
body: jsonString
});
return await response.json();
} catch (error) {
console.error(`API request to ${endpoint} failed:`, error);
throw error;
}
}
// Authentication example
async function authenticationExample() {
// API credentials - replace with actual values
const apiCredentials = {
username: 'your_api_username', // Replace with your API username
password: 'your_api_password' // Replace with your API password
};
// User credentials - replace with actual values
const userCredentials = {
email: 'user@example.com', // Replace with actual user email
password: 'user_password' // Replace with actual user password
};
try {
// Step 1: Login
console.log('Logging in...');
const loginResponse = await makeApiRequest('login.php', {}, apiCredentials);
if (loginResponse.status !== 'OK') {
throw new Error(`Login failed: ${loginResponse.message}`);
}
console.log('Login successful.');
// Logout
console.log('Logging out...');
const logoutResponse = await makeApiRequest('logout.php', {}, apiCredentials);
if (logoutResponse.status === 'ok' || logoutResponse.status === 'OK') {
console.log('Logout successful.');
} else {
console.error('Logout failed:', logoutResponse.message);
}
} catch (error) {
console.error('Authentication flow error:', error);
}
}