Skip to main content

API Key Module

The apikey module manages SDK API keys for authentication and access control.

Import

const apikey = await brdzSDK.apikey;

Methods Overview (5 methods)

MethodDescriptionAuth RequiredHTTP Endpoint
createCreate new API keyPOST /keys/sdk-key
listList all API keysGET /keys/sdk-key
removeRemove API keyDELETE /keys/sdk-key/:api_key
removePostRemove API key via POSTPOST /keys/sdk-key/delete
generatePublicGenerate public API keyPOST /keys/generate-sdk-key

Legend: ✅ = Auth Required, ❌ = No Auth Required

Example Usage

// Generate public API key (no auth required)
const publicKey = await apikey.generatePublic('My Application');
console.log('Public API Key:', publicKey.api_key);

// Create authenticated API key
const newKey = await apikey.create('Production App');
console.log('New API Key:', newKey.api_key);

// List all API keys
const keys = await apikey.list();
console.log('Total keys:', keys.data.length);

// Remove API key (preferred method)
await apikey.remove('api-key-to-remove');

// Remove API key via POST (workaround)
await apikey.removePost('api-key-to-remove');

🧩 Your API Key Building Blocks

🔑 Key Generation Blocks

  • generatePublic - Generate API key without authentication (quick start)
  • create - Create API key with user authentication (managed keys)

📋 Key Management Blocks

  • list - View all your API keys with usage statistics
  • remove - Delete API key via DELETE request
  • removePost - Delete API key via POST request (workaround)

🏗️ Common API Key Patterns

Pattern 1: "I want to get started quickly"

Generate public key → Configure SDK → Start using APIs

Use: generatePublic

Pattern 2: "I want to manage multiple keys"

Authenticate → Create keys → List keys → Remove old keys

Use: createlistremove

Pattern 3: "I need to rotate keys securely"

Create new key → Update applications → Test → Remove old key

Use: createremove


🔑 Key Generation Operations

generatePublic

Generate API key without authentication - perfect for getting started quickly.

// Generate with default name
const defaultKey = await apikey.generatePublic();
console.log('API Key:', defaultKey.api_key);
console.log('Provider:', defaultKey.provider_name); // "SDK Client"

// Generate with custom name
const customKey = await apikey.generatePublic('My Mobile App');
console.log('API Key:', customKey.api_key);
console.log('Provider:', customKey.provider_name); // "My Mobile App"
console.log('Created:', customKey.created_at);

Parameters:

  • provider_name (string, optional) - Name for your application (default: 'SDK Client')

Returns: API key object with provider name and creation timestamp

Note: This is a public endpoint that doesn't require authentication - ideal for initial setup.

create

Create API key with user authentication for managed key lifecycle.

// Create with default name
const managedKey = await apikey.create();
console.log('API Key:', managedKey.api_key);
console.log('User ID:', managedKey.user_id);

// Create with custom name
const productionKey = await apikey.create('Production Environment');
console.log('API Key:', productionKey.api_key);
console.log('Provider:', productionKey.provider_name);
console.log('Created:', productionKey.created_at);

Parameters:

  • provider_name (string, optional) - Name for your application (default: 'SDK Client')

Returns: API key object with user association and metadata

Requirements: JWT token authentication required


📋 Key Management Operations

list

List all API keys associated with your authenticated account.

// Get all API keys
const keysList = await apikey.list();

console.log(`Total keys: ${keysList.data.length}`);

keysList.data.forEach(key => {
console.log(`Key: ${key.api_key.substring(0, 12)}...`);
console.log(` Provider: ${key.provider_name}`);
console.log(` Created: ${key.created_at}`);
console.log(` Last used: ${key.last_used}`);
console.log(` Usage count: ${key.usage_count}`);
});

Returns: Array of API key metadata (actual key values are truncated for security)

Requirements: JWT token authentication required

remove

Remove API key using HTTP DELETE method.

// Remove specific API key
const apiKeyToRemove = 'f868a9cdc377916bcc33b93b5035f70b180df048b1d041e94d7f157c1464c4e7';

await apikey.remove(apiKeyToRemove);
console.log('API key removed successfully');

// Remove with error handling
try {
await apikey.remove('invalid-key-id');
} catch (error) {
if (error.message.includes('not found')) {
console.log('API key not found or not owned by user');
}
}

Parameters:

  • api_key (string, required) - Full API key to remove

Returns: Deletion confirmation

Requirements: JWT token authentication required

removePost

Remove API key using HTTP POST method (workaround for DELETE endpoint issues).

// Remove API key via POST (alternative method)
const apiKeyToRemove = 'f868a9cdc377916bcc33b93b5035f70b180df048b1d041e94d7f157c1464c4e7';

await apikey.removePost(apiKeyToRemove);
console.log('API key removed via POST method');

// Use when DELETE method fails
try {
await apikey.remove(apiKeyToRemove);
} catch (error) {
console.log('DELETE failed, trying POST method...');
await apikey.removePost(apiKeyToRemove);
}

Parameters:

  • api_key (string, required) - Full API key to remove

Returns: Deletion confirmation

Requirements: JWT token authentication required

Note: This is a workaround method when the DELETE endpoint has issues.


🚀 Complete API Key Workflows

Workflow 1: Quick Start Setup

// Complete quick start workflow
async function quickStartSetup() {
console.log('Setting up API access...');

// Step 1: Generate public API key (no auth needed)
const apiKey = await apikey.generatePublic('My New Project');
console.log(`Generated API key: ${apiKey.api_key.substring(0, 12)}...`);

// Step 2: Configure SDK
const config = await brdzSDK.config;
config.setBaseUrl('https://api.brdz.link/api');
config.setApiKey(apiKey.api_key);

// Step 3: Test API access
const countries = await brdzSDK.users.getCountryList();
console.log(`API working! Found ${countries.countries.length} countries`);

return apiKey.api_key;
}

Workflow 2: Authenticated Key Management

// Complete authenticated key management workflow
async function manageAPIKeys() {
console.log('Managing API keys...');

// Step 1: List existing keys
const existingKeys = await apikey.list();
console.log(`Current keys: ${existingKeys.data.length}`);

// Step 2: Create new key for production
const productionKey = await apikey.create('Production Environment');
console.log(`Created production key: ${productionKey.api_key.substring(0, 12)}...`);

// Step 3: Create new key for development
const devKey = await apikey.create('Development Environment');
console.log(`Created development key: ${devKey.api_key.substring(0, 12)}...`);

// Step 4: Remove old keys if needed
const oldKeys = existingKeys.data.filter(key =>
key.provider_name === 'Old Application' &&
new Date(key.last_used) < new Date(Date.now() - 30 * 24 * 60 * 60 * 1000) // 30 days old
);

for (const oldKey of oldKeys) {
await apikey.remove(oldKey.api_key);
console.log(`Removed old key: ${oldKey.provider_name}`);
}

return {
production_key: productionKey.api_key,
development_key: devKey.api_key
};
}

Workflow 3: Key Rotation Strategy

// Complete key rotation workflow
async function rotateAPIKey(oldKeyId, applicationName) {
console.log(`Rotating API key for ${applicationName}...`);

// Step 1: Create new key
const newKey = await apikey.create(`${applicationName} - ${new Date().toISOString().split('T')[0]}`);
console.log(`New key created: ${newKey.api_key.substring(0, 12)}...`);

// Step 2: Update your applications with new key
console.log('⚠️ Update your applications with the new key before proceeding');
console.log(`New API Key: ${newKey.api_key}`);

// Step 3: Wait for confirmation (in real app, this would be user input)
console.log('Waiting for application update confirmation...');
// await waitForUserConfirmation(); // Your implementation

// Step 4: Test new key (optional)
const tempConfig = await brdzSDK.config;
const originalKey = tempConfig.getApiKey();
tempConfig.setApiKey(newKey.api_key);

try {
await brdzSDK.users.getCountryList();
console.log('✅ New key is working correctly');
} catch (error) {
console.log('❌ New key test failed:', error.message);
tempConfig.setApiKey(originalKey);
throw new Error('Key rotation failed - new key not working');
}

// Step 5: Remove old key
try {
await apikey.remove(oldKeyId);
console.log('✅ Old key removed successfully');
} catch (error) {
console.log('⚠️ DELETE failed, trying POST method...');
await apikey.removePost(oldKeyId);
console.log('✅ Old key removed via POST method');
}

return newKey.api_key;
}

Workflow 4: Key Usage Analytics

// API key usage analytics workflow
async function analyzeKeyUsage() {
console.log('Analyzing API key usage...');

// Get all keys with usage data
const keysList = await apikey.list();

const analytics = {
total_keys: keysList.data.length,
active_keys: 0,
unused_keys: 0,
high_usage_keys: [],
old_keys: []
};

const thirtyDaysAgo = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);

keysList.data.forEach(key => {
const lastUsed = new Date(key.last_used);
const isRecent = lastUsed > thirtyDaysAgo;

if (isRecent) {
analytics.active_keys++;
} else {
analytics.unused_keys++;
}

if (key.usage_count > 1000) {
analytics.high_usage_keys.push({
provider: key.provider_name,
usage: key.usage_count,
last_used: key.last_used
});
}

const createdDate = new Date(key.created_at);
const ninetyDaysAgo = new Date(Date.now() - 90 * 24 * 60 * 60 * 1000);

if (createdDate < ninetyDaysAgo && !isRecent) {
analytics.old_keys.push({
provider: key.provider_name,
created: key.created_at,
last_used: key.last_used,
api_key: key.api_key
});
}
});

console.log('📊 API Key Analytics:');
console.log(` Total keys: ${analytics.total_keys}`);
console.log(` Active (used in 30 days): ${analytics.active_keys}`);
console.log(` Unused (not used in 30 days): ${analytics.unused_keys}`);
console.log(` High usage keys (>1000 requests): ${analytics.high_usage_keys.length}`);
console.log(` Old unused keys (>90 days, unused): ${analytics.old_keys.length}`);

// Suggest cleanup
if (analytics.old_keys.length > 0) {
console.log('\n🧹 Cleanup suggestions:');
analytics.old_keys.forEach(key => {
console.log(` Consider removing: ${key.provider} (created ${key.created})`);
});
}

return analytics;
}

🎯 When to Use Which Method

Getting Started

  • Quick setup: generatePublic (no authentication needed)
  • First-time users: Use public generation to test API access

Production Usage

  • Managed keys: create (requires authentication)
  • Multiple environments: Create separate keys for dev/staging/prod
  • Team usage: Create keys per team member or service

Key Management

  • View keys: list (see all keys with usage stats)
  • Remove keys: remove (preferred) or removePost (fallback)
  • Rotation: create new → update apps → remove old

💡 Pro Tips for API Key Management

Security Best Practices

// Environment-based key management
class APIKeyManager {
static getEnvironmentKey() {
const env = process.env.NODE_ENV || 'development';

switch (env) {
case 'production':
return process.env.BRDZ_PROD_API_KEY;
case 'staging':
return process.env.BRDZ_STAGING_API_KEY;
default:
return process.env.BRDZ_DEV_API_KEY;
}
}

static async setupSDK() {
const config = await brdzSDK.config;
config.setBaseUrl(process.env.BRDZ_API_BASE || 'https://api.brdz.link/api');
config.setApiKey(this.getEnvironmentKey());
}
}

Error Handling

// Robust error handling for API key operations
async function safeKeyOperation(operation) {
try {
return await operation();
} catch (error) {
if (error.message.includes('not found')) {
return { error: 'key_not_found', suggestion: 'verify_key_id' };
} else if (error.message.includes('not owned')) {
return { error: 'permission_denied', suggestion: 'check_ownership' };
} else if (error.message.includes('rate limit')) {
return { error: 'rate_limited', suggestion: 'wait_and_retry' };
} else {
console.error('Unexpected API key error:', error.message);
throw error;
}
}
}

Key Naming Strategy

// Consistent key naming for better management
class KeyNamingStrategy {
static generateName(environment, service, version) {
const timestamp = new Date().toISOString().split('T')[0];
return `${environment}-${service}-v${version}-${timestamp}`;
}

static async createEnvironmentKey(env, service) {
const name = this.generateName(env, service, '1.0');
return await apikey.create(name);
}
}

// Usage
const prodKey = await KeyNamingStrategy.createEnvironmentKey('prod', 'webapp');
const devKey = await KeyNamingStrategy.createEnvironmentKey('dev', 'mobile');

Fallback Deletion Strategy

// Reliable key deletion with fallback
async function reliableKeyDeletion(keyId) {
try {
// Try DELETE method first
await apikey.remove(keyId);
console.log('✅ Key deleted via DELETE method');
} catch (error) {
if (error.response?.status === 405 || error.message.includes('Method Not Allowed')) {
console.log('⚠️ DELETE not supported, using POST fallback...');
await apikey.removePost(keyId);
console.log('✅ Key deleted via POST method');
} else {
throw error;
}
}
}

🔐 Authentication Requirements

Different methods have different authentication requirements:

// Public method (no auth required)
await apikey.generatePublic('Quick Start App');

// Authenticated methods (JWT token + API key required)
const config = await brdzSDK.config;
config.setToken('your-jwt-token');
config.setApiKey('your-api-key');

await apikey.create('Authenticated App');
await apikey.list();
await apikey.remove('key-to-remove');
await apikey.removePost('key-to-remove');

🌍 Environment Configuration

Required Environment Variables

# Development
BRDZ_DEV_API_KEY=your_dev_key_here

# Staging
BRDZ_STAGING_API_KEY=your_staging_key_here

# Production
BRDZ_PROD_API_KEY=your_production_key_here

# API Base URL
BRDZ_API_BASE=https://api.brdz.link/api

Key Lifecycle Management

  • Generation: Use generatePublic for quick setup, create for managed keys
  • Usage: Monitor with list method for usage statistics
  • Rotation: Regular rotation (monthly/quarterly) for security
  • Deletion: Use remove primarily, removePost as fallback

Quick Start

Use generatePublic() to get an API key immediately without authentication. Perfect for testing and initial setup!

Delete Method Fallback

If remove() fails, use removePost() as a workaround. The POST method provides the same functionality when DELETE endpoint has issues.

Key Management

Monitor key usage with list() method. Remove unused keys regularly and implement key rotation for better security practices.