SDK Usage Guide

Interact with the CloudNexus platform programmatically. This guide covers installation, authentication, core methods, and best practices for building scalable infrastructure automation.

💡 SDK Versions

This documentation covers @cloudnexus/sdk v3.x. For legacy v2.x documentation, visit the version archive.

Installation

Install the official CloudNexus SDK using your preferred package manager.

bash
npm install @cloudnexus/sdk # or yarn add @cloudnexus/sdk # or pnpm add @cloudnexus/sdk
bash
pip install cloudnexus
bash
go get github.com/cloudnexus/sdk-go/v3

Authentication

Initialize the SDK using API keys. We recommend using environment variables for security.

javascript
import { CloudNexus } from '@cloudnexus/sdk'; // Initialize with environment variables const cn = new CloudNexus() { apiKey: process.env.CN_API_KEY, project: process.env.CN_PROJECT_ID, region: 'us-east-1' // Optional: defaults to auto-detect };
Variable Description Required
CN_API_KEY Your secret API key from the CloudNexus dashboard Yes
CN_PROJECT_ID Project identifier for resource isolation Yes
CN_REGION Default deployment region No

Quick Start

Create and deploy a VPS instance in under 10 lines of code.

javascript
async function createInstance() { try { const instance = await cn.vps.create({ name: 'app-server-prod', plan: 'cn-std-8vcpu-32gb', region: 'eu-west-2', image: 'ubuntu-22.04-lts', sshKeys: ['ssh-rsa AAAAB3NzaC1...'], tags: { env: 'production', team: 'platform' } }); console.log(`Instance created: ${instance.id} at ${instance.ipv4} `); return instance; } catch (error) { console.error('Failed to create instance:', error); throw error; } }

Core Methods

The SDK exposes resource managers for all CloudNexus services. Each manager follows a consistent CRUD pattern.

cn.vps.create(config)

Provisions a new virtual server with specified resources, image, and networking.

cn.k8s.deployCluster(params)

Deploys a managed Kubernetes cluster with auto-scaling and integrated load balancers.

cn.storage.createBucket(opts)

Creates an S3-compatible object storage bucket with lifecycle policies.

cn.db.provision(database, version, region)

Provisions a managed database instance with automated backups and failover.

Auto-Scaling Configuration

Define scaling policies directly through the SDK. The platform handles horizontal/vertical adjustments automatically.

javascript
const scalingPolicy = await cn.scaling.createPolicy({ target: 'instance-group:prod-web', rules: [ { metric: 'cpu_utilization', operator: '>', threshold: 80, action: 'scale_out', cooldown: 120 // seconds }, { metric: 'memory_usage', operator: '<', threshold: 30, action: 'scale_in', cooldown: 300 } ], minInstances: 2, maxInstances: 20 });

Error Handling

The SDK throws typed errors for all API failures. Catch and handle them using the provided error classes.

javascript
import { CloudNexusError, RateLimitError, ValidationError } from '@cloudnexus/sdk/errors'; try { await cn.vps.create(config); } catch (err) { if (err instanceof RateLimitError) { console.warn('Rate limited. Retrying in', err.retryAfter, 'seconds'); } else if (err instanceof ValidationError) { console.error('Invalid configuration:', err.details); } else { console.error('API Error:', err.message, err.statusCode); } }

Error Reference

Error Class HTTP Status Common Causes
AuthenticationError 401 Invalid/expired API key, missing project scope
ValidationError 400 Malformed request body, unsupported region/plan
RateLimitError 429 Exceeded request quota, missing exponential backoff
ResourceConflictError 409 Duplicate name, resource already in target state
QuotaExceededError 403 Project limit reached, require tier upgrade

Advanced Configuration

Customize HTTP client behavior, timeouts, and retry policies for production workloads.

javascript
const cn = new CloudNexus() { apiKey: process.env.CN_API_KEY, project: process.env.CN_PROJECT_ID, // Advanced options http: { timeout: 10000, // 10s request timeout retries: 3, retryStrategy: 'exponential', maxRetryDelay: 5000 }, logging: { level: 'warn', // 'debug' | 'info' | 'warn' | 'error' format: 'json' }, baseURL: 'https://api.cloudnexus.dev/v3' // Override for edge regions };