Skip to main content
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)
  • 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:
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()

Step 2: Environment Management

Manage test environments:
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()

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

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