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

# Creating

> Create new sandboxes from templates with custom configuration. Learn how to create isolated cloud environments using HopX templates, configure resources, set environment variables, and manage sandbox lifecycle. Includes Python and JavaScript SDK examples and REST API endpoints.

Sandboxes are isolated, ephemeral cloud environments where your code runs. This guide shows you how to create sandboxes from templates with custom configuration options.

## Prerequisites

Before you begin, make sure you have:

* **HopX API key** - Get one from [console.hopx.dev](https://console.hopx.dev) or see \[API key Management]\(/API key)
* **SDK installed** - Python SDK (`pip install hopx-ai`) or JavaScript SDK (`npm install @hopx-ai/sdk`)
* **Basic understanding** - Familiarity with the [Quickstart Guide](https://docs.hopx.ai/quickstart.md) is helpful

## Overview

When you create a sandbox, HopX:

* Spins up a lightweight VM in seconds (\~100ms)
* Loads resources (CPU, memory, disk) from the template
* Provides a persistent filesystem during the sandbox lifecycle
* Auto-destroys the sandbox after timeout (if configured)

> [!NOTE]
>
> Resources (vcpu, memory, disk) are **always** loaded from the template. You cannot specify custom resources when creating a sandbox. To use different resources, create a custom template first.

## Basic Creation

The simplest way to create a sandbox is using a template name:

> [tab] Python
>
> ```python theme={null}
> from hopx_ai import Sandbox
>
> # Create sandbox from template name
> sandbox = Sandbox.create(template="code-interpreter")
>
> print(f"Sandbox ID: {sandbox.sandbox_id}")
> info = sandbox.get_info()
> print(f"Status: {info.status}")
> print(f"URL: {info.public_host}")
>
> # Clean up when done
> sandbox.kill()
> ```
>
> **Expected Output:**
>
> ```
> Sandbox ID: sandbox_abc123xyz
> Status: running
> URL: https://sandbox_abc123xyz.hopx.dev
> ```

> [tab] JavaScript
>
> ```javascript theme={null}
> import { Sandbox } from '@hopx-ai/sdk';
>
> // Create sandbox from template name
> const sandbox = await Sandbox.create({
>   template: 'code-interpreter'
> });
>
> console.log(`Sandbox ID: ${sandbox.sandboxId}`);
> const info = await sandbox.getInfo();
> console.log(`Status: ${info.status}`);
> console.log(`URL: ${info.publicHost}`);
>
> // Clean up when done
> await sandbox.kill();
> ```
>
> **Expected Output:**
>
> ```
> Sandbox ID: sandbox_abc123xyz
> Status: running
> URL: https://sandbox_abc123xyz.hopx.dev
> ```

## Using Template ID

You can also create a sandbox using a template ID instead of a name:

> [tab] Python
>
> ```python theme={null}
> from hopx_ai import Sandbox
>
> # Create from template ID
> sandbox = Sandbox.create(template_id="119")
>
> # Cleanup when done
> sandbox.kill()
> ```
>
> **Expected Output:**
>
> ```
> Sandbox created successfully
> ```

> [tab] JavaScript
>
> ```javascript theme={null}
> import { Sandbox } from '@hopx-ai/sdk';
>
> // Create from template ID
> const sandbox = await Sandbox.create({
>   templateId: '119'
> });
>
> // Cleanup when done
> await sandbox.kill();
> ```
>
> **Expected Output:**
>
> ```
> Sandbox created successfully
> ```

## Configuration Options

When creating a sandbox, you can configure several options:

### Timeout

Set an auto-kill timeout to automatically destroy the sandbox after a specified duration:

> [tab] Python
>
> ```python theme={null}
> from hopx_ai import Sandbox
>
> # Create with 1 hour timeout
> sandbox = Sandbox.create(
>     template="code-interpreter",
>     timeout_seconds=3600  # 1 hour
> )
>
> info = sandbox.get_info()
> if info.expires_at:
>     print(f"Sandbox expires at: {info.expires_at}")
> ```
>
> **Expected Output:**
>
> ```
> Sandbox expires at: 2025-01-27T11:30:00Z
> ```

> [tab] JavaScript
>
> ```javascript theme={null}
> import { Sandbox } from '@hopx-ai/sdk';
>
> // Create with 1 hour timeout
> const sandbox = await Sandbox.create({
>   template: 'code-interpreter',
>   timeoutSeconds: 3600  // 1 hour
> });
>
> const info = await sandbox.getInfo();
> if (info.expiresAt) {
>   console.log(`Sandbox expires at: ${info.expiresAt}`);
> }
> ```
>
> **Expected Output:**
>
> ```
> Sandbox expires at: 2025-01-27T11:30:00Z
> ```

### Internet Access

Control whether the sandbox has internet access:

> [tab] Python
>
> ```python theme={null}
> from hopx_ai import Sandbox
>
> # Create without internet access (isolated)
> sandbox = Sandbox.create(
>     template="code-interpreter",
>     internet_access=False
> )
>
> info = sandbox.get_info()
> print(f"Internet access: {info.internet_access}")
>
> # Try to fetch an online resource to demonstrate lack of internet connectivity
> result = sandbox.run_code("""
> import urllib.request
> import urllib.error
>
> try:
>     response = urllib.request.urlopen('https://www.hopx.ai', timeout=10)
>     print(f"✅ Successfully fetched hopx.ai - Status: {response.status}")
>     print(f"Content-Type: {response.headers.get('Content-Type')}")
> except urllib.error.URLError as e:
>     print(f"❌ Failed to fetch URL: {e.reason}")
> except Exception as e:
>     print(f"❌ Error: {type(e).__name__}: {e}")
> """, language="python")
>
> print("Fetch attempt output:")
> print(result.stdout)
> if result.stderr:
>     print("Errors:")
>     print(result.stderr)
>
> if result.exit_code != 0:
>     print("\n❌ Code execution failed")
> elif "Failed to fetch" in result.stdout or "Error:" in result.stdout:
>     print("\n❌ As expected, the fetch failed. Sandbox does not have internet access.")
> else:
>     print("\n✅ Unexpected: fetch succeeded, internet access is enabled!")
>
> # Clean up when done
> sandbox.kill()
>
> ```

> [tab] JavaScript
>
> ```javascript theme={null}
> import { Sandbox } from '@hopx-ai/sdk';
>
> // Create without internet access (isolated)
> const sandbox = await Sandbox.create({
>   template: 'code-interpreter',
>   internetAccess: false
> });
>
> const info = await sandbox.getInfo();
> console.log(`Internet access: ${info.internetAccess}`);
>
> // Try to fetch an online resource to demonstrate lack of internet connectivity
> const result = await sandbox.runCode(`
> const https = require('https');
>
> function fetchUrl(url) {
>   return new Promise((resolve, reject) => {
>     https.get(url, (res) => {
>       console.log(\`✅ Successfully fetched hopx.ai - Status: \${res.statusCode}\`);
>       console.log(\`Content-Type: \${res.headers['content-type']}\`);
>       resolve();
>     }).on('error', (err) => {
>       console.log(\`❌ Failed to fetch URL: \${err.message}\`);
>       reject(err);
>     });
>   });
> }
>
> fetchUrl('https://www.hopx.ai').catch((err) => {
>   console.log(\`❌ Error: \${err.name}: \${err.message}\`);
> });
> `, { language: 'javascript' });
>
> console.log('Fetch attempt output:');
> console.log(result.stdout);
> if (result.stderr) {
>   console.log('Errors:');
>   console.log(result.stderr);
> }
>
> if (result.exitCode !== 0) {
>   console.log('\n❌ Code execution failed');
> } else if (result.stdout.includes('Failed to fetch') || result.stdout.includes('Error:')) {
>   console.log('\n❌ As expected, the fetch failed. Sandbox does not have internet access.');
> } else {
>   console.log('\n✅ Unexpected: fetch succeeded, internet access is enabled!');
> }
>
> // Clean up when done
> await sandbox.kill();
> ```

### Environment Variables

Set initial environment variables when creating the sandbox:

> [tab] Python
>
> ```python theme={null}
> from hopx_ai import Sandbox
>
> # Create with environment variables
> sandbox = Sandbox.create(
>     template="code-interpreter",
>     env_vars={
>         "API_KEY": "sk-123",
>         "DEBUG": "true",
>         "ENVIRONMENT": "production"
>     }
> )
>
> # Verify environment variables
> result = sandbox.run_code(
>     "import os; print(dict(os.environ))",
>     language="python"
> )
> print(result.stdout)  
>
> # Clean up when done
> sandbox.kill()
> ```
>
> **Expected Output:**
>
> ```
> {'API_KEY': 'sk-123', 'DEBUG': 'true', 'ENVIRONMENT': 'production', 'PATH': '/usr/local/bin:/usr/bin:/bin', ...}
> ```

> [tab] JavaScript
>
> ```javascript theme={null}
> import { Sandbox } from '@hopx-ai/sdk';
>
> // Create with environment variables
> const sandbox = await Sandbox.create({
>   template: 'code-interpreter',
>   envVars: {
>     API_KEY: 'sk-123',
>     DEBUG: 'true',
>     ENVIRONMENT: 'production'
>   }
> });
>
> // Verify environment variables
> const result = await sandbox.runCode(
>   "import os; print(os.getenv('API_KEY'))",
>   { language: 'python' }
> );
> console.log(result.stdout);  // sk-123
>
> // Clean up when done
> await sandbox.kill();
> ```
>
> **Expected Output:**
>
> ```
> sk-123
> ```

{ /*
### Region Selection

Specify a preferred region for deployment:

<Tabs>
<Tab title="Python">
```python
from hopx_ai import Sandbox

# Create in specific region
sandbox = Sandbox.create(
  template="code-interpreter",
  region="eu-west"  # or "us-east", etc.
)

info = sandbox.get_info()
print(f"Region: {info.region}")
```

</Tab>

<Tab title="JavaScript">
```javascript
import { Sandbox } from '@hopx-ai/sdk';

// Create in specific region
const sandbox = await Sandbox.create({
template: 'code-interpreter',
region: 'eu-west'  // or 'us-east', etc.
});

const info = await sandbox.getInfo();
console.log(`Region: ${info.region}`);
```

</Tab>
</Tabs>
*/}

## Using Context Managers (Python)

Python SDK supports context managers for automatic cleanup:

```python theme={null}
from hopx_ai import Sandbox

# Automatically cleans up when exiting the context
with Sandbox.create(template="code-interpreter") as sandbox:
    result = sandbox.run_code('print("Hello from HopX!")')
    print(result.stdout)
    # Sandbox is automatically deleted when exiting the block
```

**Expected Output:**

```
Hello from HopX!
```

> [!NOTE]
>
> The context manager automatically calls `sandbox.kill()` when exiting the `with` block, even if an error occurs. This ensures proper cleanup.

## Finding Available Templates

Before creating a sandbox, you may want to list available templates:

> [tab] Python
>
> ```python theme={null}
> from hopx_ai import Sandbox
>
> # List all templates
> templates = Sandbox.list_templates()
> for template in templates:
>     print(f"{template.name}: {template.display_name}")
>
> # Get specific template details
> template = Sandbox.get_template("code-interpreter")
> print(f"Description: {template.description}")
> print(f"Default resources: {template.default_resources.vcpu} vCPU")
> ```

> [tab] JavaScript
>
> ```javascript theme={null}
> import { Sandbox } from '@hopx-ai/sdk';
>
> // List all templates
> const templates = await Sandbox.listTemplates();
> for (const template of templates) {
>   console.log(`${template.name}: ${template.displayName}`);
> }
>
> // Get specific template details
> const template = await Sandbox.getTemplate('code-interpreter');
> console.log(`Description: ${template.description}`);
> console.log(`Default resources: ${template.defaultResources.vcpu} vCPU`);
> ```

## Best Practices

**1. 1. Always Clean Up**

Use context managers (Python) or try/finally blocks to ensure sandboxes are cleaned up, even if errors occur.

**2. 2. Set Appropriate Timeouts**

Set timeouts based on your use case. For quick scripts, use shorter timeouts. For long-running tasks, set longer timeouts or use timeout management.

**3. 3. Use Environment Variables**

Set environment variables at creation time rather than later for better performance and consistency.

**4. 4. Choose the Right Template**

Select templates that match your needs. Use `list_templates()` to find available options.

**5. 5. Handle Errors Gracefully**

Always handle potential errors (template not found, resource limits, etc.) in your code.

## Implementation

* **SDK**: [Sandbox.create()](https://docs.hopx.ai/sdk/python/sandbox.md#create) - Python SDK method
* **[CLI](https://docs.hopx.ai/cli/introduction.md)** - Command-line interface
* **API**: [POST /v1/sandboxes](https://docs.hopx.ai/api/control-plane/create-sandbox.md) - Control Plane API endpoint

## Related

* **[Listing Templates](https://docs.hopx.ai/core-concepts/templates/listing.md)** - Find available templates
* **[Getting Template Details](https://docs.hopx.ai/core-concepts/templates/getting-details.md)** - View template information
* **[Connecting to Sandboxes](https://docs.hopx.ai/core-concepts/sandboxes/connecting.md)** - Connect to existing sandboxes
* **[Managing Sandbox State](https://docs.hopx.ai/core-concepts/sandboxes/managing-state.md)** - Control sandbox lifecycle

## Next Steps

* Learn how to [List Sandboxes](https://docs.hopx.ai/core-concepts/sandboxes/listing.md) to find existing sandboxes
* Understand [Connecting to Existing](https://docs.hopx.ai/core-concepts/sandboxes/connecting.md) sandboxes
* Explore [Managing State](https://docs.hopx.ai/core-concepts/sandboxes/managing-state.md) (start, stop, pause, resume)
* Configure [Timeout Management](https://docs.hopx.ai/core-concepts/sandboxes/timeout.md) for long-running sandboxes


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.