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

# Quickstart

> Get started with HopX - your first HopX sandbox running in less than 2 minutes. Complete quickstart guide for creating sandboxes, executing code, and managing resources using Python SDK, JavaScript SDK, CLI, or REST API.

Get up and running with HopX; this guide walks you through creating your first sandbox, executing code, and cleaning up.

## What You'll Learn

In this quickstart, you'll learn how to:

* Install and set up the HopX SDK (Python or JavaScript) or CLI
* Create your first sandbox from a pre-built template
* Execute code in multiple languages (Python, JavaScript, Bash, Go)
* Work with files in sandboxes (read, write, list)
* Clean up sandboxes to free resources
* Use context managers for automatic cleanup (Python)

## Prerequisites

* [HopX API key](https://console.hopx.dev) (get one [here](/api-key) if you don't have it)
* Python 3.8+ **or** Node.js 18+ **or** CLI installed
* Basic experience with Python, JavaScript, or command line

## Run your first sandbox

Choose your preferred method: **Python SDK**, **JavaScript SDK**, or **CLI**. This guide focuses on SDKs. For CLI, see the [CLI Quickstart](/cli/quickstart).

<Steps>
  <Step title="Install the SDK or CLI">
    Install the HopX SDK for your preferred language, or use the CLI:

    <Tabs>
      <Tab title="Python">
        ```bash theme={null}
        pip install hopx-ai
        ```
      </Tab>

      <Tab title="JavaScript">
        ```bash theme={null}
        npm install @hopx-ai/sdk
        ```
      </Tab>

      <Tab title="CLI">
        ```bash theme={null}
        # Quick install
        curl -fsSL https://hopx.dev/install.sh | sh
        ```

        See [CLI Installation](/cli/installation) for more options.
      </Tab>
    </Tabs>
  </Step>

  <Step title="Create Your First Sandbox">
    Create a sandbox using a pre-built template. Templates provide pre-configured environments with common tools and packages.

    <Tabs>
      <Tab title="Python">
        ```python theme={null}
        from hopx_ai import Sandbox
        from hopx_ai.exceptions import APIError, ResourceLimitError

        try:
            # Create a sandbox with the code-interpreter template
            sandbox = Sandbox.create(
                template="code-interpreter",
                api_key="your-api-key-here"  # Or set HOPX_API_KEY env var
            )

            print(f"Sandbox created: {sandbox.sandbox_id}")
            print(f"Status: {sandbox.get_info().status}")
        except APIError as e:
            print(f"API error: {e}")
        except ResourceLimitError as e:
            print(f"Resource limit exceeded: {e}")
        ```

        **Expected Output:**

        ```
        Sandbox created: sandbox_abc123xyz
        Status: running
        ```

        <Note>
          You can also use <code>Sandbox.create()</code> without specifying an API key if you set the <code>HOPX\_API\_KEY</code> environment variable.
        </Note>
      </Tab>

      <Tab title="JavaScript">
        ```typescript theme={null}
        import { Sandbox } from '@hopx-ai/sdk';
        import { APIError, ResourceLimitError } from '@hopx-ai/sdk';

        try {
          // Create a sandbox with the code-interpreter template
          const sandbox = await Sandbox.create({
            template: 'code-interpreter',
            apiKey: 'your-api-key-here'  // Or set HOPX_API_KEY env var
          });

          console.log(`Sandbox created: ${sandbox.sandboxId}`);
          const info = await sandbox.getInfo();
          console.log(`Status: ${info.status}`);
        } catch (error) {
          if (error instanceof APIError) {
            console.error(`API error: ${error.message}`);
          } else if (error instanceof ResourceLimitError) {
            console.error(`Resource limit exceeded: ${error.message}`);
          } else {
            console.error(`Unexpected error: ${error.message}`);
          }
        }
        ```

        **Expected Output:**

        ```
        Sandbox created: sandbox_abc123xyz
        Status: running
        ```

        <Note>
          You can also use <code>Sandbox.create()</code> without specifying an API key if you set the <code>HOPX\_API\_KEY</code> environment variable.
        </Note>
      </Tab>
    </Tabs>
  </Step>

  <Step title="Execute Code">
    Run code in your sandbox.

    <Tabs>
      <Tab title="Python">
        ```python theme={null}
        # Execute Python code
        result = sandbox.run_code('''
        import math

        # Calculate the area of a circle
        radius = 5
        area = math.pi * radius ** 2
        print(f"Area of circle with radius {radius}: {area:.2f}")
        ''', language: 'python')

        print(result.stdout)
        # Output: Area of circle with radius 5: 78.54

        # Check if execution was successful
        if result.success:
            print("✅ Code executed successfully!")
        else:
            print(f"❌ Error: {result.stderr}")
        ```

        <Check>
          The <code>run\_code()</code> method automatically captures rich outputs like matplotlib plots and pandas DataFrames. See [Rich Output Capture](/core-concepts/code-execution/rich-output) for more details.
        </Check>
      </Tab>

      <Tab title="JavaScript">
        ```typescript theme={null}
        // Execute JavaScript code
        const result = await sandbox.runCode(`
        const radius = 5;
        const area = Math.PI * radius ** 2;
        console.log(\`Area of circle with radius \${radius}: \${area.toFixed(2)}\`);
        `, { language: 'javascript' });

        console.log(result.stdout);
        // Output: Area of circle with radius 5: 78.54

        // Check if execution was successful
        if (result.success) {
          console.log('✅ Code executed successfully!');
        } else {
          console.log(`❌ Error: ${result.stderr}`);
        }
        ```
      </Tab>
    </Tabs>

    <Note>
      The sandbox will execute code written in any language as long as the template you use provides the necessary dependencies. <br /><br />
      See the <a href="/templates/getting-template-details">Getting Template Details</a> page for information on available templates and their environments, alternatively create your own template with the <a href="/templates/building">Building Templates</a> guide.
    </Note>
  </Step>

  <Step title="Work with Files">
    Upload, read, and write files in your sandbox:

    <Tabs>
      <Tab title="Python">
        ```python theme={null}
        # Write a file
        sandbox.files.write('/workspace/data.txt', 'Hello, HopX!')

        # Read the file
        content = sandbox.files.read('/workspace/data.txt')
        print(content)  # Output: Hello, HopX!

        # List files in a directory
        files = sandbox.files.list('/workspace')
        for file in files:
            print(f"- {file.name} ({file.size} bytes)")
        ```

        **Expected Output:**

        ```
        Hello, HopX!
        - data.txt (12 bytes)
        - script.py (245 bytes)
        ```
      </Tab>

      <Tab title="JavaScript">
        ```typescript theme={null}
        // Write a file
        await sandbox.files.write('/workspace/data.txt', 'Hello, HopX!');

        // Read the file
        const content = await sandbox.files.read('/workspace/data.txt');
        console.log(content);  // Output: Hello, HopX!

        // List files in a directory
        const files = await sandbox.files.list('/workspace');
        files.forEach(file => {
          console.log(`- ${file.name} (${file.size} bytes)`);
        });
        ```

        **Expected Output:**

        ```
        Hello, HopX!
        - data.txt (12 bytes)
        - script.js (189 bytes)
        ```
      </Tab>
    </Tabs>
  </Step>

  <Step title="Clean Up">
    Always clean up your sandbox when you're done to free resources:

    <Tabs>
      <Tab title="Python">
        ```python theme={null}
        # Delete the sandbox
        sandbox.kill()
        print("Sandbox deleted")
        ```

        **Expected Output:**

        ```
        Sandbox deleted
        ```
      </Tab>

      <Tab title="JavaScript">
        ```typescript theme={null}
        // Delete the sandbox
        await sandbox.kill();
        console.log('Sandbox deleted');
        ```

        **Expected Output:**

        ```
        Sandbox deleted
        ```
      </Tab>
    </Tabs>

    <Warning>
      Calling <code>kill()</code> permanently deletes the sandbox and all its data. Make sure you've saved any important files before cleaning up.
      See [Downloading Files](./core-concepts/filesystem/downloading) for more details.
    </Warning>
  </Step>
</Steps>

## 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!")', language='python')
    print(result.stdout)
    # Sandbox is automatically deleted when exiting the block
```

**Expected Output:**

```
Hello from HopX!
```

***

## Complete Example

Here's a complete example that brings it all together:

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    from hopx_ai import Sandbox

    # Setup your API key as an env var or inject it here as previously instructed.
    # Create sandbox
    sandbox = Sandbox.create(template="code-interpreter") 

    try:
        # Execute code
        result = sandbox.run_code('''
    import math

    # Calculate the area of a circle
    radius = 5
    area = math.pi * radius ** 2
    print(f"Area of circle with radius {radius}: {area:.2f}")
        ''', language='python')
        
        print("Output:")
        print(result.stdout)

        sandbox.run_code('mkdir /workspace/test')
        
        # Work with files
        sandbox.files.write('/workspace/test/result.json', result.stdout)
        print("\n✅ Result saved to file")

        # List files in a directory
        files = sandbox.files.list('/workspace/test')
        for file in files:
            print(f"- {file.name} ({file.size} bytes)")\

        # Read the file
        content = sandbox.files.read('/workspace/test/result.json')
        print(content)
        
    finally:
        # Always clean up
        sandbox.kill()
        print("✅ Sandbox cleaned up")
    ```
  </Tab>

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

    async function main() {
      // Create sandbox
      const sandbox = await Sandbox.create({ template: 'code-interpreter'});

      try {
        // Execute JavaScript code
        const result = await sandbox.runCode(`
    const radius = 5;
    const area = Math.PI * radius ** 2;
    console.log(\`Area of circle with radius \${radius}: \${area.toFixed(2)}\`);
        `, { language: 'javascript' });
        console.log('Output:');
        console.log(result.stdout);
        console.log(result.stderr);

        // Work with files
        await sandbox.files.write('/workspace/test/result.json', result.stdout);
        console.log('\n✅ Result saved to file');

        // List files in a directory
        const files = await sandbox.files.list('/workspace/test');
        console.log(files);

        // Read the file
        const content = await sandbox.files.read('/workspace/test/result.json');
        console.log(content);

      } finally {
        // Always clean up
        await sandbox.kill();
        console.log('✅ Sandbox cleaned up');
      }
    }

    main();
    ```
  </Tab>
</Tabs>

## Related

* **[Python SDK Quickstart](/sdk/python/quickstart)** - Detailed Python SDK guide
* **[JavaScript SDK Quickstart](/sdk/javascript/quickstart)** - Detailed JavaScript SDK guide
* **[CLI Quickstart](/cli/quickstart)** - Command-line interface quickstart
* **[API Quickstart](/api/quickstart)** - API-based quickstart
* **[Creating Sandboxes](/core-concepts/sandboxes/creating)** - Learn more about sandbox creation
* **[Code Execution](/core-concepts/code-execution/synchronous)** - Learn about code execution

## Next Steps

Now that you've created your first sandbox, explore more:

* **Learn about sandbox lifecycle**: [Creating Sandboxes](/core-concepts/sandboxes/creating)
* **Execute code in different ways**: [Code Execution](/core-concepts/code-execution/synchronous)
* **Work with templates**: [Templates](/core-concepts/templates/listing)
* **Integrate with MCP**: [MCP Integration](/guides/integrations/mcp-integration)
* **Explore the SDK**: [Python SDK Reference](/sdk/python/introduction) or [JavaScript SDK Reference](/sdk/javascript/introduction)
* **Use the CLI**: [CLI Reference](/cli/introduction) - Command-line interface for HopX
* **Check supported languages**: [Supported Languages](/supported-languages)

<Tip>
  For AI agent developers, check out the [MCP Integration guide](/guides/integrations/mcp-integration) to enable AI assistants to execute code safely in sandboxes.
</Tip>
