Ready-to-use code snippets for the most common DRIP API tasks. Just copy, paste, and customize! πŸš€
New to APIs? Each example includes error handling and comments explaining what’s happening. Perfect for learning!

Setup & Authentication

Basic API Client Setup

class DripClient {
  constructor(apiKey, realmId) {
    this.apiKey = apiKey;
    this.realmId = realmId;
    this.baseUrl = 'https://api.drip.re/api/v1';
  }

  async request(method, endpoint, data = null) {
    const url = `${this.baseUrl}${endpoint}`;
    const options = {
      method,
      headers: {
        'Authorization': `Bearer ${this.apiKey}`,
        'Content-Type': 'application/json'
      }
    };

    if (data) {
      options.body = JSON.stringify(data);
    }

    try {
      const response = await fetch(url, options);
      
      if (!response.ok) {
        const error = await response.json();
        throw new Error(`API Error: ${response.status} - ${error.message || 'Unknown error'}`);
      }

      return response.json();
    } catch (error) {
      console.error('DRIP API Error:', error);
      throw error;
    }
  }
}

// Usage
const client = new DripClient('your_api_key', 'your_realm_id');

Member Management

Search for Members

// Search by different identifiers
async function searchMembers(client, searchType, values) {
  const endpoint = `/realm/${client.realmId}/members/search?type=${searchType}&values=${values}`;
  return await client.request('GET', endpoint);
}

// Examples
const client = new DripClient('your_api_key', 'your_realm_id');

// Search by Discord ID
const discordMembers = await searchMembers(client, 'discord-id', '123456789012345678');

// Search by multiple usernames
const usernameMembers = await searchMembers(client, 'username', 'user1,user2,user3');

// Search by wallet address
const walletMembers = await searchMembers(client, 'wallet', '0x742d35Cc6634C0532925a3b8D23');

// Search by email
const emailMembers = await searchMembers(client, 'email', '[email protected]');

console.log('Found members:', discordMembers.data);

Get Member Details

async function getMemberDetails(client, memberId) {
  // First search for the member to get their full details
  const members = await searchMembers(client, 'drip-id', memberId);
  
  if (members.data && members.data.length > 0) {
    const member = members.data[0];
    
    return {
      id: member.id,
      name: member.displayName || member.username,
      joinedAt: member.joinedAt,
      lastVisit: member.lastVisit,
      points: member.pointBalances || [],
      credentials: member.credentials || []
    };
  }
  
  throw new Error('Member not found');
}

// Usage
try {
  const member = await getMemberDetails(client, 'member_id_here');
  console.log(`${member.name} has ${member.points[0]?.balance || 0} points`);
} catch (error) {
  console.error('Member not found:', error.message);
}

Points Management

Award Points to a Member

async function awardPoints(client, memberId, points, realmPointId = null) {
  const endpoint = `/realm/${client.realmId}/members/${memberId}/point-balance`;
  const data = { tokens: points };
  
  if (realmPointId) {
    data.realmPointId = realmPointId;
  }
  
  return await client.request('PATCH', endpoint, data);
}

// Examples
const client = new DripClient('your_api_key', 'your_realm_id');

// Award 100 points (default currency)
const result = await awardPoints(client, 'member_id', 100);
console.log('Points awarded:', result);

// Award points to specific currency
const specificResult = await awardPoints(client, 'member_id', 50, 'specific_point_id');

// Deduct points (negative number)
const deductResult = await awardPoints(client, 'member_id', -25);

Batch Update Multiple Members

async function batchUpdatePoints(client, updates) {
  const endpoint = `/realm/${client.realmId}/members/transaction`;
  return await client.request('PATCH', endpoint, { updates });
}

// Example: Award points to multiple members
const updates = [
  { memberId: 'member_1', tokens: 100 },
  { memberId: 'member_2', tokens: 150 },
  { memberId: 'member_3', tokens: 75, realmPointId: 'specific_point_id' }
];

const batchResult = await batchUpdatePoints(client, updates);
console.log('Batch update result:', batchResult);

// Example: Weekly point distribution
async function weeklyPointDistribution(client, memberIds, basePoints = 50) {
  const updates = memberIds.map(memberId => ({
    memberId,
    tokens: basePoints + Math.floor(Math.random() * 50) // 50-100 points
  }));
  
  return await batchUpdatePoints(client, updates);
}

Transfer Points Between Members

async function transferPoints(client, senderId, recipientId, amount, realmPointId) {
  const endpoint = `/realm/${client.realmId}/members/${senderId}/transfer`;
  const data = {
    tokens: amount,
    recipientId: recipientId,
    realmPointId: realmPointId
  };
  
  return await client.request('PATCH', endpoint, data);
}

// Example: Transfer 100 points from one member to another
const transfer = await transferPoints(
  client,
  'sender_member_id',
  'recipient_member_id', 
  100,
  'realm_point_id'
);

console.log('Transfer successful:', transfer);

Common Patterns

Find and Reward Active Members

async function rewardActiveMembers(client, minPoints = 0, reward = 50) {
  // Get all members
  const allMembers = await searchMembers(client, 'drip-id', 'all');
  
  // Filter active members (you can customize this logic)
  const activeMembers = allMembers.data.filter(member => {
    const points = member.pointBalances[0]?.balance || 0;
    const lastVisit = new Date(member.lastVisit);
    const weekAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
    
    return points >= minPoints && lastVisit > weekAgo;
  });

  // Prepare batch update
  const updates = activeMembers.map(member => ({
    memberId: member.id,
    tokens: reward
  }));

  if (updates.length > 0) {
    const result = await batchUpdatePoints(client, updates);
    console.log(`Rewarded ${updates.length} active members with ${reward} points each`);
    return result;
  } else {
    console.log('No active members found to reward');
    return null;
  }
}

// Usage
await rewardActiveMembers(client, 100, 75); // Reward members with 100+ points who visited in last week

Create a Leaderboard

async function getLeaderboard(client, limit = 10) {
  // Get all members
  const allMembers = await searchMembers(client, 'drip-id', 'all');
  
  // Filter members with points and sort
  const leaderboard = allMembers.data
    .filter(member => member.pointBalances && member.pointBalances.length > 0)
    .map(member => ({
      id: member.id,
      name: member.displayName || member.username || 'Anonymous',
      points: member.pointBalances[0]?.balance || 0,
      joinedAt: member.joinedAt,
      lastVisit: member.lastVisit
    }))
    .sort((a, b) => b.points - a.points)
    .slice(0, limit)
    .map((member, index) => ({
      ...member,
      rank: index + 1
    }));

  return leaderboard;
}

// Usage
const topMembers = await getLeaderboard(client, 10);
console.log('Top 10 Members:');
topMembers.forEach(member => {
  console.log(`${member.rank}. ${member.name}: ${member.points} points`);
});

Discord Bot Integration

const { Client, GatewayIntentBits } = require('discord.js');

const bot = new Client({
  intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent]
});

const dripClient = new DripClient('your_drip_api_key', 'your_realm_id');

// Award points for messages
bot.on('messageCreate', async (message) => {
  if (message.author.bot) return;

  try {
    // Find member by Discord ID
    const members = await searchMembers(dripClient, 'discord-id', message.author.id);
    
    if (members.data && members.data.length > 0) {
      const memberId = members.data[0].id;
      
      // Award 5 points per message
      await awardPoints(dripClient, memberId, 5);
      
      // Optional: React to show points were awarded
      await message.react('⭐');
    }
  } catch (error) {
    console.error('Error awarding points:', error);
  }
});

// Leaderboard command
bot.on('messageCreate', async (message) => {
  if (message.content === '!leaderboard') {
    try {
      const leaderboard = await getLeaderboard(dripClient, 5);
      
      const leaderboardText = leaderboard
        .map(member => `${member.rank}. ${member.name}: ${member.points} points`)
        .join('\n');
      
      await message.reply(`πŸ† **Top 5 Members:**\n\`\`\`\n${leaderboardText}\n\`\`\``);
    } catch (error) {
      await message.reply('Sorry, I couldn\'t fetch the leaderboard right now.');
    }
  }
});

bot.login('your_discord_bot_token');

Error Handling Patterns

Robust Error Handling

async function safeApiCall(apiCall, fallbackValue = null) {
  try {
    return await apiCall();
  } catch (error) {
    console.error('API call failed:', error.message);
    
    // Handle specific error types
    if (error.message.includes('401')) {
      console.error('Authentication failed - check your API key');
    } else if (error.message.includes('403')) {
      console.error('Permission denied - check your scopes');
    } else if (error.message.includes('404')) {
      console.error('Resource not found');
    } else if (error.message.includes('429')) {
      console.error('Rate limited - slow down your requests');
    }
    
    return fallbackValue;
  }
}

// Usage
const members = await safeApiCall(
  () => searchMembers(client, 'discord-id', 'invalid_id'),
  { data: [] }
);

Quick Reference

Most Common API Calls

// Authentication & Setup
const client = new DripClient('api_key', 'realm_id');

// Get realm info
const realm = await client.request('GET', `/realms/${client.realmId}`);

// Search members
const members = await searchMembers(client, 'discord-id', 'user_id');

// Award points
await awardPoints(client, 'member_id', 100);

// Get leaderboard
const top10 = await getLeaderboard(client, 10);

// Batch update
await batchUpdatePoints(client, [
  { memberId: 'id1', tokens: 50 },
  { memberId: 'id2', tokens: 75 }
]);

Common Search Types

TypeUse CaseExample Value
discord-idFind Discord users123456789012345678
usernameFind by display namecooluser123
emailFind by email[email protected]
walletFind crypto users0x742d35Cc6634C0532925a3b8D23
twitter-idFind Twitter users987654321
drip-idFind by DRIP ID507f1f77bcf86cd799439013
Need more examples? Check out our First App tutorial for a complete working project, or browse the API Reference for detailed endpoint documentation.