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

# Execute Code

> Execute code synchronously in a sandbox and get results. Run Python, JavaScript, Bash, or Go code in isolated cloud environments using the HopX VM Agent API. Learn how to use POST /execute endpoint with code examples, error handling, and result processing.

Execute code synchronously in the sandbox. The request waits until execution completes and returns the output.

## Endpoint

```
POST /execute
```

## Request

### Headers

```
Authorization: Bearer YOUR_JWT_TOKEN
Content-Type: application/json
```

### Body Parameters

| Parameter     | Type    | Required | Description                                                        |
| ------------- | ------- | -------- | ------------------------------------------------------------------ |
| `code`        | string  | Yes      | Code to execute                                                    |
| `language`    | string  | No       | Language: `python`, `javascript`, `bash`, `go` (default: `python`) |
| `timeout`     | integer | No       | Execution timeout in seconds (default: 60, max: 300)               |
| `working_dir` | string  | No       | Working directory (default: `/workspace`)                          |
| `env`         | object  | No       | Environment variables for this execution only                      |

### Example Request

Execute Python code:

```bash theme={null}
curl -X POST https://sandbox_abc123xyz.hopx.dev/execute \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "code": "print(\"Hello from HopX!\")",
    "language": "python"
  }'
```

Execute JavaScript code:

```bash theme={null}
curl -X POST https://sandbox_abc123xyz.hopx.dev/execute \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "code": "console.log(\"Hello from Node.js!\");",
    "language": "javascript"
  }'
```

Execute with custom environment:

```bash theme={null}
curl -X POST https://sandbox_abc123xyz.hopx.dev/execute \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "code": "import os; print(os.getenv(\"MY_VAR\"))",
    "language": "python",
    "env": {
      "MY_VAR": "my_value"
    }
  }'
```

## Response

### Success (200 OK)

```json theme={null}
{
  "success": true,
  "stdout": "Hello from HopX!\n",
  "stderr": "",
  "exit_code": 0,
  "execution_time": 0.15
}
```

### Response Fields

| Field            | Type    | Description                              |
| ---------------- | ------- | ---------------------------------------- |
| `success`        | boolean | Whether execution completed successfully |
| `stdout`         | string  | Standard output                          |
| `stderr`         | string  | Standard error                           |
| `exit_code`      | integer | Exit code (0 = success)                  |
| `execution_time` | number  | Execution time in seconds                |

## Status Codes

| Code | Description                                      |
| ---- | ------------------------------------------------ |
| 200  | Execution completed                              |
| 400  | Invalid request (missing code, invalid language) |
| 401  | Unauthorized (invalid or expired JWT)            |
| 408  | Execution timeout                                |
| 500  | Execution failed                                 |

## Supported Languages

### Python

```bash theme={null}
curl -X POST https://sandbox_abc123xyz.hopx.dev/execute \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "code": "import pandas as pd\ndf = pd.DataFrame({\"a\": [1,2,3]})\nprint(df)",
    "language": "python"
  }'
```

### JavaScript (Node.js)

```bash theme={null}
curl -X POST https://sandbox_abc123xyz.hopx.dev/execute \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "code": "const fs = require(\"fs\");\nconsole.log(fs.readdirSync(\".\"));",
    "language": "javascript"
  }'
```

### Bash

```bash theme={null}
curl -X POST https://sandbox_abc123xyz.hopx.dev/execute \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "code": "ls -la /workspace",
    "language": "bash"
  }'
```

## Errors

### Timeout (408)

```json theme={null}
{
  "error": "Execution timeout after 60 seconds",
  "code": "EXECUTION_TIMEOUT"
}
```

**Cause:** Code execution exceeded the timeout limit.

**Fix:** Increase the timeout or optimize your code.

### Invalid Language (400)

```json theme={null}
{
  "error": "Invalid language: ruby",
  "code": "INVALID_REQUEST"
}
```

**Cause:** Unsupported language specified.

**Fix:** Use one of the supported languages: `python`, `javascript`, `bash`, `go`.

### Execution Failed (500)

```json theme={null}
{
  "success": false,
  "stdout": "",
  "stderr": "NameError: name 'x' is not defined\n",
  "exit_code": 1,
  "execution_time": 0.05
}
```

**Cause:** Code execution failed (syntax error, runtime error, etc.).

**Fix:** Check the `stderr` field for error details.

## Use Cases

### Data Analysis

```bash theme={null}
curl -X POST https://sandbox_abc123xyz.hopx.dev/execute \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "code": "import pandas as pd\nimport numpy as np\n\ndata = {\"sales\": [100, 150, 200, 180, 220]}\ndf = pd.DataFrame(data)\n\nprint(f\"Mean: ${df[\"sales\"].mean():.2f}\")\nprint(f\"Median: ${df[\"sales\"].median():.2f}\")",
    "language": "python"
  }'
```

### File Processing

```bash theme={null}
curl -X POST https://sandbox_abc123xyz.hopx.dev/execute \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "code": "with open(\"/workspace/data.txt\", \"r\") as f:\n    lines = f.readlines()\n    print(f\"File has {len(lines)} lines\")",
    "language": "python"
  }'
```

### System Information

```bash theme={null}
curl -X POST https://sandbox_abc123xyz.hopx.dev/execute \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "code": "import platform\nimport os\n\nprint(f\"OS: {platform.system()}\")\nprint(f\"Python: {platform.python_version()}\")\nprint(f\"CPU Count: {os.cpu_count()}\")",
    "language": "python"
  }'
```

## Related

* **SDK**: [sandbox.run\_code()](/sdk/python/sandbox#run_code) - Python SDK method
* [CLI Code Execution](/cli/commands/run) - Execute code from CLI

## Next Steps

* **[Rich Output](/api/vm-agent/execute-rich)** - Capture plots and visualizations
* **[Background Execution](/api/vm-agent/execute-background)** - Run long-running tasks
* **[Async Execution](/api/vm-agent/execute-async)** - Execute with webhook callbacks
