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

# Write File

> Write content to a file in the sandbox using the HopX VM Agent API. Create new files or overwrite existing files with text or binary content. Learn how to use POST /files/write endpoint with encoding options, file permissions, and error handling. Includes request examples and response formats.

Write content to a file in the sandbox. Creates the file if it doesn't exist, or overwrites if it does. Only allowed paths can be written.

## Endpoint

```
POST /files/write
```

## Request

### Headers

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

### Body Parameters

| Parameter | Type   | Required | Description           |
| --------- | ------ | -------- | --------------------- |
| `path`    | string | Yes      | Destination file path |
| `content` | string | Yes      | File content to write |

### Example Request

```bash theme={null}
curl -X POST https://sandbox_abc123xyz.hopx.dev/files/write \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "path": "/workspace/data.txt",
    "content": "Hello World\nLine 2\nLine 3"
  }'
```

Write JSON file:

```bash theme={null}
curl -X POST https://sandbox_abc123xyz.hopx.dev/files/write \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "path": "/workspace/config.json",
    "content": "{\"api_key\": \"test\", \"timeout\": 30}"
  }'
```

## Response

### Success (200 OK)

```json theme={null}
{
  "path": "/workspace/data.txt",
  "size": 30,
  "message": "File written successfully"
}
```

### Response Fields

| Field     | Type    | Description          |
| --------- | ------- | -------------------- |
| `path`    | string  | File path            |
| `size`    | integer | File size in bytes   |
| `message` | string  | Confirmation message |

## Status Codes

| Code | Description                               |
| ---- | ----------------------------------------- |
| 200  | File written successfully                 |
| 400  | Invalid request (missing path or content) |
| 401  | Unauthorized                              |
| 403  | Path not allowed                          |
| 500  | Write failed                              |

## Errors

### Path Not Allowed (403)

```json theme={null}
{
  "error": "Path not allowed: /etc/config",
  "code": "FORBIDDEN"
}
```

**Cause:** The path is outside allowed directories.

**Fix:** Only write files to `/workspace`, `/tmp`, or other explicitly allowed paths.

## Use Cases

### Write Configuration

```bash theme={null}
curl -X POST https://sandbox_abc123xyz.hopx.dev/files/write \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "path": "/workspace/app_config.json",
    "content": "{\"database\": \"postgres://localhost/mydb\", \"port\": 5000}"
  }'
```

### Write Python Script

```bash theme={null}
curl -X POST https://sandbox_abc123xyz.hopx.dev/files/write \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "path": "/workspace/script.py",
    "content": "import pandas as pd\n\ndf = pd.DataFrame({\"a\": [1,2,3]})\nprint(df)\n"
  }'
```

### Write CSV Data

```bash theme={null}
curl -X POST https://sandbox_abc123xyz.hopx.dev/files/write \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "path": "/workspace/data.csv",
    "content": "Name,Age,City\nAlice,25,NYC\nBob,30,LA\nCharlie,35,SF\n"
  }'
```

### Write and Execute

```bash theme={null}
#!/bin/bash
# Write script
curl -X POST https://sandbox_abc123xyz.hopx.dev/files/write \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "path": "/workspace/hello.py",
    "content": "print(\"Hello from HopX!\")"
  }'

# Execute it
curl -X POST https://sandbox_abc123xyz.hopx.dev/execute \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "code": "exec(open(\"/workspace/hello.py\").read())",
    "language": "python"
  }'
```

### Write from Python

```python theme={null}
import requests
import json

url = "https://sandbox_abc123xyz.hopx.dev/files/write"
headers = {"Authorization": "Bearer YOUR_JWT_TOKEN"}

# Prepare data
data = {
    "users": [
        {"name": "Alice", "age": 25},
        {"name": "Bob", "age": 30}
    ]
}

payload = {
    "path": "/workspace/users.json",
    "content": json.dumps(data, indent=2)
}

response = requests.post(url, headers=headers, json=payload)
print(f"Wrote {response.json()['size']} bytes")
```

## Related

* **SDK**: [sandbox.files.write()](/sdk/python/files#write) - Python SDK method
* [CLI File Operations](/cli/commands/files) - File operations from CLI

## Next Steps

* **[Read File](/api/vm-agent/read-file)** - Read file contents
* **[List Files](/api/vm-agent/list-files)** - List directory contents
* **[Remove File](/api/vm-agent/remove-file)** - Delete files
