> ## Documentation Index
> Fetch the complete documentation index at: https://docs.hopx.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Low-Code Platform Backend

> Build a low-code/no-code platform backend with visual to code translation, script execution, integration patterns, and custom logic execution

Build a production-ready low-code platform backend that translates visual workflows to code and executes them. This cookbook demonstrates how to create a platform similar to Zapier or Microsoft Power Automate using HopX.

## Overview

Low-code platforms allow users to build applications visually without writing code. The backend translates visual workflows to executable code, executes scripts, handles integrations, and runs custom logic.

## Prerequisites

* HopX API key ([Get one here](https://console.hopx.dev/api-keys))
* Python 3.8+ or Node.js 16+
* Understanding of workflow engines
* Basic knowledge of code generation

## Architecture

```
┌──────────────┐
│  Visual      │ Workflow definition
│  Workflow    │
└──────┬───────┘
       │
       ▼
┌─────────────────┐
│  Code           │ Translate to code
│  Generator      │
└──────┬──────────┘
       │
       ▼
┌─────────────────┐
│  HopX Sandbox   │ Execute generated code
└─────────────────┘
```

## Implementation

### Step 1: Visual to Code Translation

Translate visual workflows to executable code:

<CodeGroup>
  ```python Python theme={null}
  from hopx_ai import Sandbox
  import os
  from typing import Dict, Any, List

  class WorkflowNode:
      def __init__(self, node_id: str, node_type: str, config: Dict[str, Any]):
          self.node_id = node_id
          self.node_type = node_type
          self.config = config

  class LowCodeBackend:
      def __init__(self, api_key: str):
          self.api_key = api_key
          self.sandbox = None
      
      def initialize(self):
          """Initialize backend"""
          self.sandbox = Sandbox.create(
              template="code-interpreter",
              api_key=self.api_key,
              timeout_seconds=3600
          )
      
      def translate_workflow(self, nodes: List[WorkflowNode]) -> str:
          """Translate visual workflow to code"""
          code_parts = []
          
          for node in nodes:
              if node.node_type == "trigger":
                  code_parts.append(f"# Trigger: {node.config.get('name', '')}")
              elif node.node_type == "action":
                  action_code = self._generate_action_code(node)
                  code_parts.append(action_code)
              elif node.node_type == "condition":
                  condition_code = self._generate_condition_code(node)
                  code_parts.append(condition_code)
          
          return "\n".join(code_parts)
      
      def _generate_action_code(self, node: WorkflowNode) -> str:
          """Generate code for action node"""
          action_type = node.config.get("action_type", "")
          
          if action_type == "http_request":
              return f"""
  import requests
  response = requests.{node.config.get('method', 'get').lower()}('{node.config.get('url', '')}')
  print(response.text)
  """
          elif action_type == "data_transform":
              return f"""
  data = {node.config.get('data', '{}')}
  # Transform data
  result = data
  print(result)
  """
          else:
              return f"# Action: {action_type}"
      
      def _generate_condition_code(self, node: WorkflowNode) -> str:
          """Generate code for condition node"""
          condition = node.config.get("condition", "")
          return f"""
  if {condition}:
      # Condition met
      pass
  else:
      # Condition not met
      pass
  """
      
      def execute_workflow(self, nodes: List[WorkflowNode]) -> Dict[str, Any]:
          """Execute visual workflow"""
          try:
              # Translate to code
              code = self.translate_workflow(nodes)
              
              # Execute
              result = self.sandbox.run_code(code, timeout=60)
              
              return {
                  "success": result.success,
                  "stdout": result.stdout,
                  "stderr": result.stderr,
                  "generated_code": code
              }
          except Exception as e:
              return {
                  "success": False,
                  "error": str(e)
              }
      
      def cleanup(self):
          """Clean up backend resources"""
          if self.sandbox:
              self.sandbox.kill()
              self.sandbox = None

  # Usage
  backend = LowCodeBackend(api_key=os.getenv("HOPX_API_KEY"))
  backend.initialize()

  # Define workflow
  nodes = [
      WorkflowNode("node_1", "trigger", {"name": "webhook"}),
      WorkflowNode("node_2", "action", {
          "action_type": "http_request",
          "method": "GET",
          "url": "https://api.example.com/data"
      })
  ]

  result = backend.execute_workflow(nodes)
  print(result)

  backend.cleanup()
  ```

  ```javascript JavaScript theme={null}
  import { Sandbox } from '@hopx-ai/sdk';

  class WorkflowNode {
      constructor(nodeId, nodeType, config) {
          this.nodeId = nodeId;
          this.nodeType = nodeType;
          this.config = config;
      }
  }

  class LowCodeBackend {
      constructor(apiKey) {
          this.apiKey = apiKey;
          this.sandbox = null;
      }
      
      async initialize() {
          this.sandbox = await Sandbox.create({
              template: 'code-interpreter',
              apiKey: this.apiKey,
              timeoutSeconds: 3600
          });
      }
      
      translateWorkflow(nodes) {
          const codeParts = [];
          
          for (const node of nodes) {
              if (node.nodeType === 'trigger') {
                  codeParts.push(`# Trigger: ${node.config.name || ''}`);
              } else if (node.nodeType === 'action') {
                  codeParts.push(this.generateActionCode(node));
              } else if (node.nodeType === 'condition') {
                  codeParts.push(this.generateConditionCode(node));
              }
          }
          
          return codeParts.join('\n');
      }
      
      generateActionCode(node) {
          const actionType = node.config.actionType || '';
          
          if (actionType === 'http_request') {
              return `
  import requests
  response = requests.${(node.config.method || 'get').toLowerCase()}('${node.config.url || ''}')
  print(response.text)
  `;
          } else if (actionType === 'data_transform') {
              return `
  data = ${JSON.stringify(node.config.data || {})}
  # Transform data
  result = data
  print(result)
  `;
          } else {
              return `# Action: ${actionType}`;
          }
      }
      
      generateConditionCode(node) {
          const condition = node.config.condition || '';
          return `
  if ${condition}:
      # Condition met
      pass
  else:
      # Condition not met
      pass
  `;
      }
      
      async executeWorkflow(nodes) {
          try {
              // Translate to code
              const code = this.translateWorkflow(nodes);
              
              // Execute
              const result = await this.sandbox.runCode(code, { timeout: 60 });
              
              return {
                  success: result.success,
                  stdout: result.stdout,
                  stderr: result.stderr,
                  generatedCode: code
              };
          } catch (error) {
              return {
                  success: false,
                  error: error.message
              };
          }
      }
      
      async cleanup() {
          if (this.sandbox) {
              await this.sandbox.kill();
              this.sandbox = null;
          }
      }
  }

  // Usage
  const backend = new LowCodeBackend(process.env.HOPX_API_KEY);
  await backend.initialize();

  // Define workflow
  const nodes = [
      new WorkflowNode('node_1', 'trigger', { name: 'webhook' }),
      new WorkflowNode('node_2', 'action', {
          actionType: 'http_request',
          method: 'GET',
          url: 'https://api.example.com/data'
      })
  ];

  const result = await backend.executeWorkflow(nodes);
  console.log(result);

  await backend.cleanup();
  ```
</CodeGroup>

## Best Practices

1. **Code Generation**: Generate clean, maintainable code
2. **Error Handling**: Handle translation errors gracefully
3. **Integration Patterns**: Support common integration patterns
4. **Custom Logic**: Allow custom code injection

## Related Cookbooks

* [User-Defined Functions](/cookbooks/marketplace/user-functions) - Custom functions
* [Multi-Tenant Execution](/cookbooks/enterprise/multi-tenant-execution) - Multi-tenant patterns

## Next Steps

1. Implement visual workflow builder
2. Add more node types
3. Create integration library
4. Implement workflow versioning
5. Add workflow monitoring
