Skip to content

External Integrations

This guide explains how to connect Raikoo workflows with external systems, APIs, and services to extend functionality and integrate AI orchestration into your broader technology ecosystem.

Introduction to Raikoo Integrations

Raikoo provides multiple methods for interacting with external systems:

  • API Calls - Making HTTP requests to external services
  • Webhooks - Receiving and responding to external triggers
  • Code Execution - Running custom integration code
  • Data Import/Export - Exchanging data with external systems
  • Tool Extensions - Using custom tools to connect to specific services

These integration capabilities allow you to incorporate AI workflows into existing business processes, connect with enterprise systems, and create end-to-end automation solutions.

Making API Calls

Using the Execute JavaScript Operation

The most flexible way to make API calls is through the Execute JavaScript operation:

async function callExternalApi() {
  const response = await fetch('https://api.example.com/data', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer ' + OperationParameters.ApiKey
    },
    body: JSON.stringify({
      query: Workspace.read('/query.json')
    })
  });

  if (!response.ok) {
    throw new Error(`API call failed: ${response.status} ${response.statusText}`);
  }

  return await response.json();
}

export default await callExternalApi();

Key aspects of this approach: - Uses standard fetch API for HTTP requests - Can handle authentication through operation parameters - Supports all HTTP methods (GET, POST, PUT, DELETE, etc.) - Can process the response before returning it

Handling Authentication

Secure your API integrations by:

  1. Storing API keys and credentials as operation parameters
  2. Using environment variables for sensitive information
  3. Implementing proper token management:
async function getAccessToken() {
  // Get token from authentication service
  const tokenResponse = await fetch('https://auth.example.com/token', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      client_id: OperationParameters.ClientId,
      client_secret: OperationParameters.ClientSecret,
      grant_type: 'client_credentials'
    })
  });

  const tokenData = await tokenResponse.json();
  return tokenData.access_token;
}

async function callApiWithAuth() {
  const token = await getAccessToken();

  // Use token to call the actual API
  const apiResponse = await fetch('https://api.example.com/data', {
    headers: { 'Authorization': `Bearer ${token}` }
  });

  return await apiResponse.json();
}

export default await callApiWithAuth();

Working with API Responses

Process and transform API responses for use in workflows:

async function processApiResponse() {
  const response = await fetch('https://api.example.com/data');
  const data = await response.json();

  // Transform the response into a more usable format
  const transformedData = {
    items: data.results.map(item => ({
      id: item.id,
      name: item.properties.name,
      category: item.properties.category,
      value: parseFloat(item.properties.value)
    })),
    totalCount: data.count,
    hasMore: data.next !== null
  };

  return JSON.stringify(transformedData, null, 2);
}

export default await processApiResponse();

Webhook Integrations

Receiving External Triggers

Raikoo can receive webhook notifications from external systems:

  1. Configure a webhook endpoint in your Raikoo project settings
  2. Set up the external system to send notifications to this endpoint
  3. Create workflows that process these incoming webhook payloads

The webhook payload is made available as a parameter to your workflow, which you can then process:

// Example of processing a webhook payload in Execute JavaScript
function processWebhookPayload() {
  const payload = JSON.parse(WorkflowParameters.WebhookPayload);

  // Process based on event type
  switch(payload.event_type) {
    case 'new_user':
      return handleNewUser(payload.data);
    case 'order_completed':
      return handleOrderCompleted(payload.data);
    default:
      return `Unhandled event type: ${payload.event_type}`;
  }
}

function handleNewUser(userData) {
  // Process new user data
  // ...
  return `New user ${userData.email} has been processed`;
}

function handleOrderCompleted(orderData) {
  // Process completed order
  // ...
  return `Order ${orderData.order_id} has been processed`;
}

export default processWebhookPayload();

Sending Webhook Notifications

Your workflows can send webhook notifications to other systems:

async function sendWebhookNotification() {
  const workflowResult = JSON.parse(Workspace.read('/result.json'));

  await fetch(OperationParameters.WebhookUrl, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      event: 'workflow_completed',
      workflow_id: WorkflowParameters.WorkflowId,
      timestamp: new Date().toISOString(),
      status: 'success',
      result_summary: workflowResult.summary
    })
  });

  return "Webhook notification sent successfully";
}

export default await sendWebhookNotification();

Database Integrations

Connecting to Databases

Execute SQL queries and interact with databases using JavaScript:

import { createPool } from 'mysql2/promise';

async function queryDatabase() {
  // Create a connection pool
  const pool = createPool({
    host: OperationParameters.DbHost,
    user: OperationParameters.DbUser,
    password: OperationParameters.DbPassword,
    database: OperationParameters.DbName
  });

  try {
    // Execute query
    const [rows] = await pool.query(
      'SELECT * FROM customers WHERE region = ?',
      [WorkflowParameters.Region]
    );

    return JSON.stringify(rows, null, 2);
  } finally {
    // End the pool
    await pool.end();
  }
}

export default await queryDatabase();

Working with ORM Libraries

For more complex database interactions, consider using ORM libraries:

import { Sequelize, DataTypes } from 'sequelize';

async function useOrmLibrary() {
  // Initialize Sequelize
  const sequelize = new Sequelize(
    OperationParameters.DbName,
    OperationParameters.DbUser,
    OperationParameters.DbPassword,
    {
      host: OperationParameters.DbHost,
      dialect: 'postgres'
    }
  );

  // Define a model
  const User = sequelize.define('User', {
    firstName: DataTypes.STRING,
    lastName: DataTypes.STRING,
    email: DataTypes.STRING
  });

  // Find users
  const users = await User.findAll({
    where: {
      lastName: WorkflowParameters.LastName
    }
  });

  return JSON.stringify(users.map(user => user.toJSON()), null, 2);
}

export default await useOrmLibrary();

File System Integrations

Reading and Writing External Files

Use the E2B operations to interact with external file systems:

// Inside an E2B: Execute JavaScript operation
const fs = require('fs');
const path = require('path');

// Read from Amazon S3 using the AWS SDK
const AWS = require('aws-sdk');
const s3 = new AWS.S3({
  accessKeyId: process.env.AWS_ACCESS_KEY_ID,
  secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY
});

async function readFromS3() {
  const params = {
    Bucket: 'my-bucket',
    Key: 'path/to/file.json'
  };

  const data = await s3.getObject(params).promise();
  return data.Body.toString();
}

// Write the result to the workspace
const s3Content = await readFromS3();
Workspace.write('/imported-data.json', s3Content);

// Return success message
export default "Successfully imported data from S3";

Working with Cloud Storage

Connect to various cloud storage providers:

// Google Cloud Storage example
const {Storage} = require('@google-cloud/storage');

async function workWithGoogleStorage() {
  // Initialize storage
  const storage = new Storage();
  const bucketName = OperationParameters.BucketName;
  const fileName = OperationParameters.FileName;

  // Download file
  const [file] = await storage.bucket(bucketName).file(fileName).download();

  // Process the file content
  const fileContent = file.toString('utf-8');
  const processedContent = processContent(fileContent);

  // Upload processed content to a different file
  await storage.bucket(bucketName)
    .file(`processed-${fileName}`)
    .save(processedContent);

  return "Successfully processed file in Google Cloud Storage";
}

function processContent(content) {
  // Process the content as needed
  return content.toUpperCase();
}

export default await workWithGoogleStorage();

Email Integration

Sending Emails

Send email notifications from your workflows:

const nodemailer = require('nodemailer');

async function sendEmailNotification() {
  // Create transporter
  let transporter = nodemailer.createTransport({
    host: OperationParameters.SmtpHost,
    port: OperationParameters.SmtpPort,
    secure: true,
    auth: {
      user: OperationParameters.SmtpUser,
      pass: OperationParameters.SmtpPassword
    }
  });

  // Generate email content from workspace file
  const emailContent = Workspace.read('/email-content.md');

  // Send mail
  let info = await transporter.sendMail({
    from: '"Raikoo Workflow" <workflow@example.com>',
    to: WorkflowParameters.RecipientEmail,
    subject: "Workflow Completion Notification",
    text: emailContent,
    html: convertMarkdownToHtml(emailContent)
  });

  return `Email sent: ${info.messageId}`;
}

function convertMarkdownToHtml(markdown) {
  // Simple markdown to HTML conversion
  // In a real scenario, use a proper markdown parser
  return markdown
    .replace(/# (.*?)\n/g, '<h1>$1</h1>')
    .replace(/## (.*?)\n/g, '<h2>$1</h2>')
    .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
    .replace(/\*(.*?)\*/g, '<em>$1</em>')
    .replace(/\n/g, '<br>');
}

export default await sendEmailNotification();

Processing Incoming Emails

Process emails through a webhook integration with an email service:

  1. Set up an email service that can forward emails to a webhook
  2. Configure a Raikoo webhook to receive these email payloads
  3. Process the email content in your workflow:
function processIncomingEmail() {
  const emailPayload = JSON.parse(WorkflowParameters.EmailPayload);

  // Extract relevant information
  const sender = emailPayload.from;
  const subject = emailPayload.subject;
  const bodyText = emailPayload.text;
  const attachments = emailPayload.attachments || [];

  // Process based on subject or content
  if (subject.includes('Report Request')) {
    return handleReportRequest(sender, bodyText);
  } else if (subject.includes('Support')) {
    return handleSupportRequest(sender, bodyText);
  }

  return `Processed email from ${sender} with subject "${subject}"`;
}

export default processIncomingEmail();

Custom Integration Tools

Creating Reusable Integration Tools

For commonly used integrations, create custom tools:

  1. Use the custom tool development framework in Raikoo
  2. Implement the integration logic in JavaScript or TypeScript
  3. Package the tool with a clear interface and documentation
  4. Make the tool available in your project or organization

Example custom tool for a CRM integration:

// CRM Integration Tool
import { Tool, ToolInput, ToolOutput } from 'raikoo-tools';

export class CrmTool implements Tool {
  name = 'CRM Tool';
  description = 'Interacts with our CRM system';

  // Define available methods
  async getCustomer(input: ToolInput): Promise<ToolOutput> {
    const customerId = input.args.customerId;

    // Implementation to fetch customer from CRM
    const customer = await this.fetchCustomerFromCrm(customerId);

    return {
      result: customer
    };
  }

  async updateCustomer(input: ToolInput): Promise<ToolOutput> {
    const customerId = input.args.customerId;
    const updates = input.args.updates;

    // Implementation to update customer in CRM
    const result = await this.updateCustomerInCrm(customerId, updates);

    return {
      result: result
    };
  }

  // Private methods for actual implementation
  private async fetchCustomerFromCrm(id: string): Promise<any> {
    // Actual implementation here
  }

  private async updateCustomerInCrm(id: string, updates: any): Promise<any> {
    // Actual implementation here
  }
}

Using Integration Tools in AI Operations

Use custom integration tools in AI-based operations:

  1. Enable the tool in your AI operation configuration
  2. The AI model can then call the tool when needed:
To retrieve customer information from our CRM, I'll use the CRM tool.

{{#tool "CRM Tool" "getCustomer" customerId="12345"}}
{{/tool}}

Based on the customer information retrieved, I can see that this customer has been with us for 3 years and has a premium subscription.

Real-World Integration Examples

CRM Integration Workflow

A workflow that processes new leads:

  1. Receive webhook notification when a new lead form is submitted
  2. Process and validate the lead information
  3. Enrich the lead with additional data from third-party services
  4. Use AI to analyze lead quality and suggest follow-up strategies
  5. Create the lead in the CRM system
  6. Assign to appropriate sales representative
  7. Generate and send a personalized introduction email

E-commerce Integration Workflow

A workflow that automates order processing:

  1. Receive notification of new order from e-commerce platform
  2. Validate order details and check inventory
  3. Process payment through payment gateway
  4. Generate personalized order confirmation
  5. Create shipping label through shipping API
  6. Update inventory management system
  7. Schedule follow-up for customer satisfaction

Content Publishing Workflow

A workflow that automates content publication:

  1. Receive draft content from a content management system
  2. Use AI to analyze and optimize the content
  3. Generate metadata, tags, and SEO recommendations
  4. Create and optimize images using external APIs
  5. Format content for different publishing channels
  6. Schedule publication through CMS API
  7. Monitor performance metrics after publication

Best Practices for Integrations

Security Considerations

  • Store sensitive credentials securely, never hardcode them
  • Use OAuth 2.0 where available for secure authentication
  • Implement proper error handling to avoid exposing sensitive information
  • Validate all incoming data from external systems
  • Use HTTPS for all external API communications

Performance Optimization

  • Implement caching for frequently accessed external data
  • Use batch operations when possible to reduce API calls
  • Handle rate limiting gracefully with exponential backoff
  • Process large datasets in chunks to avoid memory issues
  • Monitor integration performance and set up alerts for issues

Error Handling

  • Implement retry logic for transient failures
  • Create detailed error logs with contextual information
  • Design fallback mechanisms for critical integrations
  • Set up monitoring for integration health
  • Create alerts for critical integration failures

Maintainability

  • Document all integrations thoroughly
  • Use consistent patterns across different integrations
  • Version your integration code and APIs
  • Test integrations regularly with automated tests
  • Keep dependencies updated to avoid security vulnerabilities

Conclusion

External integrations expand the capabilities of Raikoo workflows, allowing them to connect with your broader technology ecosystem. By effectively integrating with APIs, databases, file systems, and other external services, you can create comprehensive automation solutions that combine the power of AI with your existing business systems.

For more specific integration needs, consider exploring the Developer Documentation for information on Raikoo's own API capabilities and how to extend the platform with custom code and tools.