> ## 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.

# API Testing Automation Platform

> Build a Postman-style API testing platform with test script execution, environment management, assertion frameworks, and test reporting

Build a production-ready API testing automation platform that executes test scripts, manages environments, validates responses, and generates reports. This cookbook demonstrates how to create a platform similar to Postman or Insomnia using HopX.

## Overview

API testing platforms allow developers to write, execute, and manage API tests. The platform executes test scripts, manages test environments, validates responses with assertions, and generates comprehensive test reports. HopX provides the secure execution environment needed for this use case.

## Prerequisites

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

## Architecture

```
┌──────────────┐
│  Test Script │ API test definition
└──────┬───────┘
       │
       ▼
┌─────────────────┐
│  Test Runner    │ Execute, validate
└──────┬──────────┘
       │
       ▼
┌─────────────────┐
│  HopX Sandbox   │ Secure execution
└──────┬──────────┘
       │
       ▼
┌─────────────────┐
│  Test Report    │ Results & metrics
└─────────────────┘
```

## Implementation

### Step 1: Basic API Test Execution

Execute API test scripts:

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

  class APITestRunner:
      def __init__(self, api_key: str):
          self.api_key = api_key
          self.sandbox = None
      
      def initialize(self):
          """Initialize test sandbox"""
          self.sandbox = Sandbox.create(
              template="code-interpreter",
              api_key=self.api_key,
              timeout_seconds=600
          )
          
          # Install requests library
          self.sandbox.commands.run("pip install requests", timeout=30)
      
      def run_test(self, test_code: str, env_vars: Dict[str, str] = None) -> Dict[str, Any]:
          """Execute API test"""
          try:
              # Set environment variables
              if env_vars:
                  self.sandbox.env.set_all(env_vars)
              
              # Execute test
              result = self.sandbox.run_code(test_code, timeout=30)
              
              # Parse test results
              test_results = self._parse_test_results(result.stdout)
              
              return {
                  "success": result.success and test_results.get("all_passed", False),
                  "stdout": result.stdout,
                  "stderr": result.stderr,
                  "test_results": test_results,
                  "execution_time": result.execution_time
              }
          except Exception as e:
              return {
                  "success": False,
                  "error": str(e)
              }
      
      def _parse_test_results(self, output: str) -> Dict[str, Any]:
          """Parse test output"""
          # Simple parsing - in production, use proper test framework
          passed = output.count("PASS") or output.count("✓")
          failed = output.count("FAIL") or output.count("✗")
          
          return {
              "all_passed": failed == 0 and passed > 0,
              "passed": passed,
              "failed": failed
          }
      
      def cleanup(self):
          """Clean up test resources"""
          if self.sandbox:
              self.sandbox.kill()
              self.sandbox = None

  # Usage
  runner = APITestRunner(api_key=os.getenv("HOPX_API_KEY"))
  runner.initialize()

  test_code = """
  import requests
  import json

  # Test GET endpoint
  response = requests.get('https://jsonplaceholder.typicode.com/posts/1')
  assert response.status_code == 200, f"Expected 200, got {response.status_code}"
  data = response.json()
  assert 'userId' in data, "Missing userId field"
  print("PASS: GET test")
  """

  result = runner.run_test(test_code)
  print(json.dumps(result, indent=2))

  runner.cleanup()
  ```

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

  class APITestRunner {
      constructor(apiKey) {
          this.apiKey = apiKey;
          this.sandbox = null;
      }
      
      async initialize() {
          this.sandbox = await Sandbox.create({
              template: 'code-interpreter',
              apiKey: this.apiKey,
              timeoutSeconds: 600
          });
          
          // Install axios
          await this.sandbox.commands.run('npm install axios', { timeout: 30 });
      }
      
      async runTest(testCode, envVars = null) {
          try {
              // Set environment variables
              if (envVars) {
                  await this.sandbox.env.setAll(envVars);
              }
              
              // Execute test
              const result = await this.sandbox.runCode(testCode, { timeout: 30 });
              
              // Parse test results
              const testResults = this.parseTestResults(result.stdout);
              
              return {
                  success: result.success && testResults.allPassed,
                  stdout: result.stdout,
                  stderr: result.stderr,
                  testResults,
                  executionTime: result.execution_time
              };
          } catch (error) {
              return {
                  success: false,
                  error: error.message
              };
          }
      }
      
      parseTestResults(output) {
          const passed = (output.match(/PASS/g) || []).length || (output.match(/✓/g) || []).length;
          const failed = (output.match(/FAIL/g) || []).length || (output.match(/✗/g) || []).length;
          
          return {
              allPassed: failed === 0 && passed > 0,
              passed,
              failed
          };
      }
      
      async cleanup() {
          if (this.sandbox) {
              await this.sandbox.kill();
              this.sandbox = null;
          }
      }
  }

  // Usage
  const runner = new APITestRunner(process.env.HOPX_API_KEY);
  await runner.initialize();

  const testCode = `
  const axios = require('axios');

  // Test GET endpoint
  const response = await axios.get('https://jsonplaceholder.typicode.com/posts/1');
  if (response.status !== 200) {
      throw new Error(\`Expected 200, got \${response.status}\`);
  }
  if (!response.data.userId) {
      throw new Error('Missing userId field');
  }
  console.log('PASS: GET test');
  `;

  const result = await runner.runTest(testCode);
  console.log(JSON.stringify(result, null, 2));

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

### Step 2: Environment Management

Manage test environments:

<CodeGroup>
  ```python Python theme={null}
  class EnvironmentManager:
      def __init__(self, sandbox: Sandbox):
          self.sandbox = sandbox
          self.environments = {}
      
      def create_environment(self, env_name: str, variables: Dict[str, str]):
          """Create test environment"""
          self.environments[env_name] = variables
      
      def use_environment(self, env_name: str):
          """Use environment for tests"""
          if env_name in self.environments:
              self.sandbox.env.set_all(self.environments[env_name])
              return True
          return False

  # Usage
  sandbox = Sandbox.create(template="code-interpreter", api_key=os.getenv("HOPX_API_KEY"))
  env_manager = EnvironmentManager(sandbox)

  env_manager.create_environment("production", {
      "API_URL": "https://api.example.com",
      "API_KEY": "prod-key-123"
  })

  env_manager.create_environment("staging", {
      "API_URL": "https://staging-api.example.com",
      "API_KEY": "staging-key-456"
  })

  env_manager.use_environment("production")
  sandbox.kill()
  ```

  ```javascript JavaScript theme={null}
  class EnvironmentManager {
      constructor(sandbox) {
          this.sandbox = sandbox;
          this.environments = {};
      }
      
      createEnvironment(envName, variables) {
          this.environments[envName] = variables;
      }
      
      async useEnvironment(envName) {
          if (this.environments[envName]) {
              await this.sandbox.env.setAll(this.environments[envName]);
              return true;
          }
          return false;
      }
  }

  // Usage
  const sandbox = await Sandbox.create({
      template: 'code-interpreter',
      apiKey: process.env.HOPX_API_KEY
  });
  const envManager = new EnvironmentManager(sandbox);

  envManager.createEnvironment('production', {
      API_URL: 'https://api.example.com',
      API_KEY: 'prod-key-123'
  });

  envManager.createEnvironment('staging', {
      API_URL: 'https://staging-api.example.com',
      API_KEY: 'staging-key-456'
  });

  await envManager.useEnvironment('production');
  await sandbox.kill();
  ```
</CodeGroup>

## Best Practices

1. **Test Isolation**: Each test should be independent
2. **Environment Management**: Use separate environments for different stages
3. **Assertion Framework**: Use proper assertion libraries
4. **Test Reporting**: Generate comprehensive test reports

## Related Cookbooks

* [Isolated Test Execution](/cookbooks/testing/isolated-test-execution) - Test isolation
* [Web Scraping Service](/cookbooks/automation/web-scraping-service) - Automation workflows

## Next Steps

1. Implement test collection management
2. Add support for multiple HTTP methods
3. Create test result visualization
4. Implement test scheduling
5. Add API mocking support
