Skip to main content

Console API Integration

Console APIs provide comprehensive functionality for organization management, team collaboration, and platform administration. This guide covers integration patterns, best practices, and real-world examples for building management tools and administrative interfaces.
Use Case: Console APIs are perfect for building internal management tools, organization administration features, and team collaboration platforms.

Integration Overview

Console APIs enable you to build powerful management tools that can:

Team Management

Create and manage teams with role-based access control and member collaboration.

Platform Administration

Create, configure, and manage platforms with domain verification and client management.

User Management

Handle user registration, authentication, and profile management.

Organization Control

Manage organization settings, billing, and subscription information.

Authentication Setup

Step 1: User Registration and Login

Register User Account

Create a new user account with organization information.
curl -X POST 'https://api.weir.ai/auth/register' \
  -H 'Content-Type: application/json' \
  -d '{
    "fullname": "John Doe",
    "email": "[email protected]",
    "password": "securePassword123",
    "organization": {
      "name": "My Company",
      "type": "Platform",
      "description": "A business platform"
    }
  }'

Validate Registration

If required, validate the registration with OTP.
curl -X POST 'https://api.weir.ai/auth/validate/registration' \
  -H 'Content-Type: application/json' \
  -d '{
    "otpSession": "otp_session_123456789",
    "otp": "123456"
  }'

Login and Get Tokens

Login to get access and refresh tokens.
curl -X POST 'https://api.weir.ai/auth/login' \
  -H 'Content-Type: application/json' \
  -d '{
    "username": "John Doe",
    "password": "securePassword123"
  }'

Step 2: Token Management

class ConsoleAPIClient {
  constructor() {
    this.baseURL = 'https://api.weir.ai';
    this.accessToken = null;
    this.refreshToken = null;
  }
  
  async login(username, password) {
    const response = await fetch(`${this.baseURL}/auth/login`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ username, password })
    });
    
    const data = await response.json();
    this.accessToken = data.data.accessToken;
    this.refreshToken = data.data.refreshToken;
    
    return data;
  }
  
  async refreshAccessToken() {
    const response = await fetch(`${this.baseURL}/auth/refresh/token`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ refreshToken: this.refreshToken })
    });
    
    const data = await response.json();
    this.accessToken = data.data.accessToken;
    this.refreshToken = data.data.refreshToken;
    
    return data;
  }
  
  getHeaders() {
    return {
      'Authorization': `Bearer ${this.accessToken}`,
      'Content-Type': 'application/json',
      'x-source': 'console'
    };
  }
}

Team Management Integration

Building a Team Management Interface

Create Team Management Class

Build a comprehensive team management class.
class TeamManager {
  constructor(apiClient) {
    this.api = apiClient;
  }
  
  async createTeam(name) {
    const response = await fetch(`${this.api.baseURL}/org/create/team`, {
      method: 'POST',
      headers: this.api.getHeaders(),
      body: JSON.stringify({ name })
    });
    
    if (!response.ok) {
      throw new Error(`Failed to create team: ${response.status}`);
    }
    
    return await response.json();
  }
  
  async getTeams(page = 1, limit = 10) {
    const response = await fetch(
      `${this.api.baseURL}/org/teams?page=${page}&limit=${limit}`,
      { headers: this.api.getHeaders() }
    );
    
    return await response.json();
  }
  
  async inviteMember(teamId, memberData) {
    const response = await fetch(
      `${this.api.baseURL}/org/invite/team/member/${teamId}`,
      {
        method: 'POST',
        headers: this.api.getHeaders(),
        body: JSON.stringify(memberData)
      }
    );
    
    return await response.json();
  }
  
  async getTeamMembers(teamId) {
    const response = await fetch(
      `${this.api.baseURL}/org/team/members/${teamId}`,
      { headers: this.api.getHeaders() }
    );
    
    return await response.json();
  }
  
  async updateMemberRole(teamId, memberId, role) {
    const response = await fetch(
      `${this.api.baseURL}/org/team/${teamId}/member/${memberId}`,
      {
        method: 'PATCH',
        headers: this.api.getHeaders(),
        body: JSON.stringify({ role })
      }
    );
    
    return await response.json();
  }
}

Implement Team Dashboard

Create a team dashboard with real-time updates.
class TeamDashboard {
  constructor(teamManager) {
    this.teamManager = teamManager;
    this.teams = [];
    this.currentTeam = null;
  }
  
  async loadTeams() {
    try {
      const response = await this.teamManager.getTeams();
      this.teams = response.data.teams;
      this.renderTeams();
    } catch (error) {
      console.error('Failed to load teams:', error);
    }
  }
  
  async createTeam(name) {
    try {
      const response = await this.teamManager.createTeam(name);
      this.teams.push(response.data);
      this.renderTeams();
      return response;
    } catch (error) {
      console.error('Failed to create team:', error);
      throw error;
    }
  }
  
  async inviteMember(teamId, memberData) {
    try {
      const response = await this.teamManager.inviteMember(teamId, memberData);
      await this.loadTeamMembers(teamId);
      return response;
    } catch (error) {
      console.error('Failed to invite member:', error);
      throw error;
    }
  }
  
  renderTeams() {
    const container = document.getElementById('teams-container');
    container.innerHTML = this.teams.map(team => `
      <div class="team-card" data-team-id="${team.teamId}">
        <h3>${team.name}</h3>
        <p>Members: ${team.memberCount}</p>
        <p>Created: ${new Date(team.createdAt).toLocaleDateString()}</p>
        <button onclick="dashboard.selectTeam('${team.teamId}')">
          Manage Team
        </button>
      </div>
    `).join('');
  }
}

Platform Management Integration

Building a Platform Administration Tool

Create Platform Manager

Build a platform management class.
class PlatformManager {
  constructor(apiClient) {
    this.api = apiClient;
  }
  
  async createPlatform(platformData) {
    const response = await fetch(`${this.api.baseURL}/org/create/platform`, {
      method: 'POST',
      headers: this.api.getHeaders(),
      body: JSON.stringify(platformData)
    });
    
    return await response.json();
  }
  
  async getPlatforms() {
    const response = await fetch(
      `${this.api.baseURL}/org/platforms`,
      { headers: this.api.getHeaders() }
    );
    
    return await response.json();
  }
  
  async verifyPlatform(platformId) {
    const response = await fetch(
      `${this.api.baseURL}/org/verify/platform/${platformId}`,
      { headers: this.api.getHeaders() }
    );
    
    return await response.json();
  }
  
  async createClient(platformId, clientData) {
    const response = await fetch(`${this.api.baseURL}/org/create/client`, {
      method: 'POST',
      headers: this.api.getHeaders(),
      body: JSON.stringify(clientData)
    });
    
    return await response.json();
  }
}

Implement Platform Dashboard

Create a platform administration dashboard.
class PlatformDashboard {
  constructor(platformManager) {
    this.platformManager = platformManager;
    this.platforms = [];
  }
  
  async loadPlatforms() {
    try {
      const response = await this.platformManager.getPlatforms();
      this.platforms = response.data;
      this.renderPlatforms();
    } catch (error) {
      console.error('Failed to load platforms:', error);
    }
  }
  
  async createPlatform(platformData) {
    try {
      const response = await this.platformManager.createPlatform(platformData);
      this.platforms.push(response.data);
      this.renderPlatforms();
      return response;
    } catch (error) {
      console.error('Failed to create platform:', error);
      throw error;
    }
  }
  
  async verifyPlatform(platformId) {
    try {
      const response = await this.platformManager.verifyPlatform(platformId);
      await this.loadPlatforms(); // Refresh to get updated status
      return response;
    } catch (error) {
      console.error('Failed to verify platform:', error);
      throw error;
    }
  }
  
  renderPlatforms() {
    const container = document.getElementById('platforms-container');
    container.innerHTML = this.platforms.map(platform => `
      <div class="platform-card" data-platform-id="${platform.platformId}">
        <h3>${platform.name}</h3>
        <p>Type: ${platform.type}</p>
        <p>Domain: ${platform.domain}</p>
        <p>Status: ${platform.status}</p>
        <p>Team: ${platform.teamId}</p>
        <div class="platform-actions">
          <button onclick="dashboard.verifyPlatform('${platform.platformId}')">
            Verify Platform
          </button>
          <button onclick="dashboard.manageClients('${platform.platformId}')">
            Manage Clients
          </button>
        </div>
      </div>
    `).join('');
  }
}

User Management Integration

Building a User Administration System

Create User Manager

Build a user management class.
class UserManager {
  constructor(apiClient) {
    this.api = apiClient;
  }
  
  async updateProfile(profileData) {
    const response = await fetch(`${this.api.baseURL}/user/profile`, {
      method: 'PATCH',
      headers: this.api.getHeaders(),
      body: JSON.stringify(profileData)
    });
    
    return await response.json();
  }
  
  async changePassword(passwordData) {
    const response = await fetch(`${this.api.baseURL}/user/change/password`, {
      method: 'PATCH',
      headers: this.api.getHeaders(),
      body: JSON.stringify(passwordData)
    });
    
    return await response.json();
  }
  
  async getProfile() {
    const response = await fetch(
      `${this.api.baseURL}/user/profile`,
      { headers: this.api.getHeaders() }
    );
    
    return await response.json();
  }
}

Implement User Profile Interface

Create a user profile management interface.
class UserProfileManager {
  constructor(userManager) {
    this.userManager = userManager;
    this.currentUser = null;
  }
  
  async loadProfile() {
    try {
      const response = await this.userManager.getProfile();
      this.currentUser = response.data;
      this.renderProfile();
    } catch (error) {
      console.error('Failed to load profile:', error);
    }
  }
  
  async updateProfile(profileData) {
    try {
      const response = await this.userManager.updateProfile(profileData);
      this.currentUser = { ...this.currentUser, ...response.data };
      this.renderProfile();
      return response;
    } catch (error) {
      console.error('Failed to update profile:', error);
      throw error;
    }
  }
  
  async changePassword(passwordData) {
    try {
      const response = await this.userManager.changePassword(passwordData);
      return response;
    } catch (error) {
      console.error('Failed to change password:', error);
      throw error;
    }
  }
  
  renderProfile() {
    if (!this.currentUser) return;
    
    const container = document.getElementById('profile-container');
    container.innerHTML = `
      <div class="profile-form">
        <h2>User Profile</h2>
        <form id="profile-form">
          <div class="form-group">
            <label for="firstname">First Name:</label>
            <input type="text" id="firstname" value="${this.currentUser.firstname || ''}" />
          </div>
          <div class="form-group">
            <label for="lastname">Last Name:</label>
            <input type="text" id="lastname" value="${this.currentUser.lastname || ''}" />
          </div>
          <div class="form-group">
            <label for="email">Email:</label>
            <input type="email" id="email" value="${this.currentUser.email || ''}" />
          </div>
          <div class="form-group">
            <label for="bio">Bio:</label>
            <textarea id="bio">${this.currentUser.bio || ''}</textarea>
          </div>
          <div class="form-group">
            <label for="location">Location:</label>
            <input type="text" id="location" value="${this.currentUser.location || ''}" />
          </div>
          <button type="submit">Update Profile</button>
        </form>
      </div>
    `;
    
    document.getElementById('profile-form').addEventListener('submit', async (e) => {
      e.preventDefault();
      const formData = {
        firstname: document.getElementById('firstname').value,
        lastname: document.getElementById('lastname').value,
        email: document.getElementById('email').value,
        bio: document.getElementById('bio').value,
        location: document.getElementById('location').value
      };
      
      try {
        await this.updateProfile(formData);
        alert('Profile updated successfully!');
      } catch (error) {
        alert('Failed to update profile. Please try again.');
      }
    });
  }
}

Error Handling and Best Practices

Comprehensive Error Handling

class ConsoleAPIError extends Error {
  constructor(message, code, details, status) {
    super(message);
    this.name = 'ConsoleAPIError';
    this.code = code;
    this.details = details;
    this.status = status;
  }
}

class ConsoleAPIClient {
  async makeRequest(url, options = {}) {
    try {
      const response = await fetch(url, {
        ...options,
        headers: {
          ...this.getHeaders(),
          ...options.headers
        }
      });
      
      if (!response.ok) {
        const errorData = await response.json();
        throw new ConsoleAPIError(
          errorData.error?.message || 'API request failed',
          errorData.error?.code || 'UNKNOWN_ERROR',
          errorData.error?.details,
          response.status
        );
      }
      
      return await response.json();
    } catch (error) {
      if (error instanceof ConsoleAPIError) {
        throw error;
      }
      
      // Handle network errors
      if (error.name === 'TypeError' && error.message.includes('fetch')) {
        throw new ConsoleAPIError(
          'Network error: Unable to connect to API',
          'NETWORK_ERROR',
          null,
          0
        );
      }
      
      throw new ConsoleAPIError(
        'Unexpected error occurred',
        'UNEXPECTED_ERROR',
        error.message,
        0
      );
    }
  }
}

Rate Limiting and Retry Logic

class RateLimitedClient {
  constructor(apiClient, requestsPerMinute = 200) {
    this.apiClient = apiClient;
    this.requestsPerMinute = requestsPerMinute;
    this.requestQueue = [];
    this.requestCount = 0;
    this.windowStart = Date.now();
    
    setInterval(() => {
      this.requestCount = 0;
      this.windowStart = Date.now();
      this.processQueue();
    }, 60000);
  }
  
  async makeRequest(url, options = {}) {
    return new Promise((resolve, reject) => {
      this.requestQueue.push({ url, options, resolve, reject });
      this.processQueue();
    });
  }
  
  async processQueue() {
    if (this.requestQueue.length === 0 || this.requestCount >= this.requestsPerMinute) {
      return;
    }
    
    const request = this.requestQueue.shift();
    this.requestCount++;
    
    try {
      const result = await this.apiClient.makeRequest(request.url, request.options);
      request.resolve(result);
    } catch (error) {
      if (error.status === 429) {
        // Rate limited, put request back in queue
        this.requestQueue.unshift(request);
        setTimeout(() => this.processQueue(), 60000);
      } else {
        request.reject(error);
      }
    }
  }
}

Integration Examples

Complete Management Dashboard

class ManagementDashboard {
  constructor() {
    this.apiClient = new ConsoleAPIClient();
    this.teamManager = new TeamManager(this.apiClient);
    this.platformManager = new PlatformManager(this.apiClient);
    this.userManager = new UserManager(this.apiClient);
    
    this.teamDashboard = new TeamDashboard(this.teamManager);
    this.platformDashboard = new PlatformDashboard(this.platformManager);
    this.userProfileManager = new UserProfileManager(this.userManager);
  }
  
  async initialize() {
    try {
      // Load initial data
      await Promise.all([
        this.teamDashboard.loadTeams(),
        this.platformDashboard.loadPlatforms(),
        this.userProfileManager.loadProfile()
      ]);
      
      this.setupEventListeners();
    } catch (error) {
      console.error('Failed to initialize dashboard:', error);
    }
  }
  
  setupEventListeners() {
    // Setup navigation and form handlers
    document.getElementById('create-team-btn').addEventListener('click', () => {
      this.showCreateTeamModal();
    });
    
    document.getElementById('create-platform-btn').addEventListener('click', () => {
      this.showCreatePlatformModal();
    });
  }
  
  showCreateTeamModal() {
    const modal = document.getElementById('create-team-modal');
    modal.style.display = 'block';
    
    document.getElementById('team-form').addEventListener('submit', async (e) => {
      e.preventDefault();
      const name = document.getElementById('team-name').value;
      
      try {
        await this.teamDashboard.createTeam(name);
        modal.style.display = 'none';
        document.getElementById('team-form').reset();
      } catch (error) {
        alert('Failed to create team. Please try again.');
      }
    });
  }
  
  showCreatePlatformModal() {
    const modal = document.getElementById('create-platform-modal');
    modal.style.display = 'block';
    
    document.getElementById('platform-form').addEventListener('submit', async (e) => {
      e.preventDefault();
      const platformData = {
        name: document.getElementById('platform-name').value,
        teamId: document.getElementById('team-id').value,
        description: document.getElementById('platform-description').value,
        type: document.getElementById('platform-type').value,
        domain: document.getElementById('platform-domain').value
      };
      
      try {
        await this.platformDashboard.createPlatform(platformData);
        modal.style.display = 'none';
        document.getElementById('platform-form').reset();
      } catch (error) {
        alert('Failed to create platform. Please try again.');
      }
    });
  }
}

// Initialize dashboard when page loads
document.addEventListener('DOMContentLoaded', async () => {
  const dashboard = new ManagementDashboard();
  await dashboard.initialize();
});

Best Practices Summary

  • Implement automatic token refresh before expiration
  • Store tokens securely and never expose them in client-side code
  • Handle authentication errors gracefully with proper user feedback
  • Use different tokens for different environments
  • Implement comprehensive error handling for all API operations
  • Provide clear error messages to users
  • Log errors for debugging without exposing sensitive information
  • Handle network failures and timeouts gracefully
  • Cache responses when possible to reduce API calls
  • Use pagination for large datasets
  • Implement retry logic with exponential backoff
  • Monitor rate limit headers to avoid hitting limits
  • Provide loading states and progress indicators
  • Implement optimistic updates for better responsiveness
  • Use proper form validation and error display
  • Provide clear feedback for all user actions
Pro Tip: Start with the Team Management APIs to set up your organization structure, then use Platform Management APIs to create and configure your platforms. The User Management APIs will help you build comprehensive user administration features.