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

> How to obtain, manage, and use your HopX API keys for authentication. Complete guide to API key management, security best practices, and configuration for HopX SDK, CLI, and API access.

Your API key is required to authenticate all requests to the HopX API. This guide shows you how to get your API key, configure it securely, and use it with the SDKs, CLI, or REST API.

## Get Your API key

Sign up at [console.hopx.dev](https://console.hopx.dev) to get your free API key. After creating an account, you'll find your API key in the dashboard.

<Note>
  Your API key is shown only once when created. Make sure to save it securely. If you lose your key, you'll need to create a new one.
</Note>

## API key Format

HopX API keys follow this format:

```
hopx_live_<keyId>.<secret>
```

**Example:**

```
hopx_live_NXAXAV4sU3Ii.EXi3vR9kOJuhfbR5z42aFx5rhGjH1xnzFdjn9caAqps
```

<Warning>
  Never share your API key publicly or commit it to version control. Treat it like a password.
</Warning>

## Setting Your API key

You can provide your API key in several ways. The SDKs check these sources in order:

### Method 1: Environment Variable (Recommended)

Set the `HOPX_API_KEY` environment variable. This is the most secure method and keeps your key out of your code.

<Tabs>
  <Tab title="Python">
    ```bash theme={null}
    # Linux/macOS
    export HOPX_API_KEY="hopx_live_..."

    # Windows (PowerShell)
    $env:HOPX_API_KEY="hopx_live_..."

    # Windows (Command Prompt)
    set HOPX_API_KEY=hopx_live_...
    ```

    Then use the SDK without specifying the key:

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

    # API key is automatically read from HOPX_API_KEY environment variable
    sandbox = Sandbox.create(template="code-interpreter")
    ```
  </Tab>

  <Tab title="JavaScript">
    ```bash theme={null}
    # Linux/macOS
    export HOPX_API_KEY="hopx_live_..."

    # Windows (PowerShell)
    $env:HOPX_API_KEY="hopx_live_..."

    # Windows (Command Prompt)
    set HOPX_API_KEY=hopx_live_...
    ```

    Then use the SDK without specifying the key:

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

    // API key is automatically read from HOPX_API_KEY environment variable
    const sandbox = await Sandbox.create({ template: 'code-interpreter' });
    ```
  </Tab>
</Tabs>

### Method 2: Pass Directly to SDK

You can pass the API key directly when creating a sandbox:

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

    sandbox = Sandbox.create(
        template="code-interpreter",
        api_key="hopx_live_..."  # Pass directly
    )
    ```
  </Tab>

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

    const sandbox = await Sandbox.create({
        template: 'code-interpreter',
        apiKey: 'hopx_live_...'  // Pass directly
    });
    ```
  </Tab>
</Tabs>

<Warning>
  Avoid hardcoding API keys in your source code. Use environment variables or secure secret management systems instead.
</Warning>

### Method 3: Configuration File

You can use configuration files or secret management systems:

<Tabs>
  <Tab title="Python (.env file)">
    ```bash theme={null}
    # .env file
    HOPX_API_KEY=hopx_live_...
    ```

    ```python theme={null}
    # Install python-dotenv: pip install python-dotenv
    from dotenv import load_dotenv
    load_dotenv()

    from hopx_ai import Sandbox

    # API key is automatically loaded from .env
    sandbox = Sandbox.create(template="code-interpreter")
    ```
  </Tab>

  <Tab title="JavaScript (.env file)">
    ```bash theme={null}
    # .env file
    HOPX_API_KEY=hopx_live_...
    ```

    ```javascript theme={null}
    // Install dotenv: npm install dotenv
    import 'dotenv/config';
    import { Sandbox } from '@hopx-ai/sdk';

    // API key is automatically loaded from .env
    const sandbox = await Sandbox.create({ template: 'code-interpreter' });
    ```
  </Tab>

  <Tab title="CLI">
    The CLI automatically uses the `HOPX_API_KEY` environment variable. You can also configure it via:

    ```bash theme={null}
    # Set environment variable
    export HOPX_API_KEY="hopx_live_..."

    # Or use CLI login (interactive)
    hopx auth login

    # Or set via CLI config
    hopx config set api_key "hopx_live_..."
    ```

    See [CLI Authentication](/cli/commands/auth) for more options.
  </Tab>
</Tabs>

## Using API Keys with Direct API Calls

When making direct HTTP requests to the HopX API, include your API key in the request headers:

### Header Format

You can use either of these header formats:

```bash theme={null}
# Option 1: Authorization header (recommended)
Authorization: Bearer hopx_live_...

# Option 2: X-API-Key header
X-API-Key: hopx_live_...
```

### Example: Creating a Sandbox

```bash theme={null}
curl -X POST https://api.hopx.dev/v1/sandboxes \
  -H "Authorization: Bearer hopx_live_..." \
  -H "Content-Type: application/json" \
  -d '{
    "template_id": "code-interpreter"
  }'
```

### Example: Listing Sandboxes

```bash theme={null}
curl https://api.hopx.dev/v1/sandboxes \
  -H "Authorization: Bearer hopx_live_..."
```

## Security Best Practices

<Steps>
  <Step title="1. Store Keys Securely">
    Never commit API keys to version control. Use environment variables, secret management services (AWS Secrets Manager, HashiCorp Vault), or secure configuration files.
  </Step>

  <Step title="2. Rotate Keys Regularly">
    Periodically rotate your API keys, especially if you suspect they may have been compromised. Create new keys in the console and update your applications.
  </Step>

  <Step title="3. Use Different Keys for Different Environments">
    Use separate API keys for development, staging, and production environments. This allows you to revoke access to specific environments without affecting others.
  </Step>

  <Step title="4. Monitor Key Usage">
    Regularly review your API key usage in the console to detect any unauthorized access or unusual activity.
  </Step>

  <Step title="5. Restrict Key Permissions">
    If your organization supports it, create API keys with limited permissions for specific use cases (e.g., read-only keys for monitoring).
  </Step>
</Steps>

## Testing Your API key

You can test your API key by making a simple API call:

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

    try:
        # Try to list templates (requires valid API key)
        templates = Sandbox.list_templates()
        print(f"✅ API key is valid! Found {len(templates)} templates.")
    except Exception as e:
        print(f"❌ API key error: {e}")
    ```

    **Expected Output:**

    ```
    ✅ API key is valid! Found 15 templates.
    ```
  </Tab>

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

    try {
        // Try to list templates (requires valid API key)
        const templates = await Sandbox.listTemplates();
        console.log(`✅ API key is valid! Found ${templates.length} templates.`);
    } catch (error) {
        console.error(`❌ API key error: ${error.message}`);
    }
    ```

    **Expected Output:**

    ```
    ✅ API key is valid! Found 15 templates.
    ```
  </Tab>

  <Tab title="cURL">
    ```bash theme={null}
    curl https://api.hopx.dev/v1/templates \
      -H "Authorization: Bearer hopx_live_..."
    ```

    If your key is valid, you'll receive a JSON response with available templates. If invalid, you'll get a `401 Unauthorized` error.
  </Tab>
</Tabs>

## Troubleshooting

### Invalid API key Error

If you receive an authentication error:

1. **Verify the key format**: Ensure your key starts with `hopx_live_` and contains both the key ID and secret separated by a dot.
2. **Check for extra spaces**: Make sure there are no leading or trailing spaces when copying the key.
3. **Verify environment variable**: If using environment variables, confirm it's set correctly:
   ```bash theme={null}
   echo $HOPX_API_KEY  # Linux/macOS
   echo %HOPX_API_KEY%  # Windows
   ```
4. **Check key status**: Log into [console.hopx.dev](https://console.hopx.dev) to verify your key is active and not revoked.

### Key Not Found

If the SDK can't find your API key:

1. **Check environment variable name**: Ensure it's exactly `HOPX_API_KEY` (case-sensitive on some systems).
2. **Restart your terminal/IDE**: Environment variables may not be loaded in your current session.
3. **Verify the key is set**: Use the troubleshooting commands above to confirm the variable is set.

### Rate Limiting

If you receive rate limit errors:

* Your API key has usage limits based on your plan
* Wait a few moments and retry your request
* Consider implementing exponential backoff in your application
* Upgrade your plan if you need higher rate limits

## Related

* **[API Authentication](/api/authentication)** - Learn about API authentication
* **[Python SDK Quickstart](/sdk/python/quickstart)** - Get started with the Python SDK
* **[JavaScript SDK Quickstart](/sdk/javascript/quickstart)** - Get started with the JavaScript SDK
* **[API Quickstart](/api/quickstart)** - Make your first API request

## Next Steps

* Follow the [Quickstart Guide](/quickstart) to create your first sandbox
* Learn about [Supported Languages](/supported-languages) for code execution
* Explore [MCP Integration](/guides/integrations/mcp-integration) for AI assistant integration
