> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.xapi.to/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.xapi.to/_mcp/server.

# 写入文件

POST https://sandbox.xapi.to/v1/sandboxes/{id}/files
Content-Type: application/json

向运行中实例写入 UTF-8 文本或 base64 编码内容。用于上传任务输入和脚本。

Reference: https://docs.xapi.to/sandbox/api-reference/execution/write-file

## Authentication

- `XAPI-Key` header (required) — 在 xAPI Console 创建的 API Key。只会发送给 *.xapi.to。

## Servers

- `https://sandbox.xapi.to` (Production, default)
- `https://sandbox.test.xapi.to` (Test)

## Request

### Path parameters

- `id` (string, required) — xAPI Sandbox 实例 UUID。

### Body (application/json)

This endpoint expects a FileWriteRequest.

- `path` (string, required) — 相对于工作区的目标路径；不能包含父目录跳转片段。
- `content` (string, required) — utf8 时为原始文本；base64 时为不带 `data:*;base64,` 前缀的 Base64 字符串。
- `encoding` (enum, required) — content 的编码方式；二进制文件必须使用 base64。
  - Allowed values: `utf8`, `base64`

## Response

### 201

写入结果

- `path` (string, optional) — 实际写入或规范化后的工作区路径。
- `written` (boolean, optional) — 供应商是否确认写入完成。
- `bytes` (integer, optional) — 实际写入字节数；供应商未返回时省略。

## Errors

### 409 Conflict Error

实例状态不允许当前操作，或已有状态变更正在执行

- `statusCode` (integer, optional) — HTTP 状态码的数值形式，例如 400、401、402、404、409 或 429。
- `message` (ErrorMessage, optional) — 面向调用方的错误原因；校验失败时可能是多条消息数组。
- `error` (string, optional) — HTTP 错误类别，例如 Bad Request、Unauthorized 或 Conflict。

## Types

### ErrorMessage

面向调用方的错误原因；校验失败时可能是多条消息数组。

- string
- list of string

## Examples

**Request**

```json
{
  "path": "input.txt",
  "content": "Hello from the xAPI Sandbox API Explorer.",
  "encoding": "utf8"
}
```

**Response**

```json
{
  "path": "input.txt",
  "written": true
}
```

**SDK Code**

```python
import requests

url = "https://sandbox.xapi.to/v1/sandboxes/33333333-3333-4333-8333-333333333333/files"

payload = {
    "path": "input.txt",
    "content": "Hello from the xAPI Sandbox API Explorer.",
    "encoding": "utf8"
}
headers = {
    "XAPI-Key": "<apiKey>",
    "Content-Type": "application/json"
}

response = requests.post(url, json=payload, headers=headers)

print(response.json())
```

```javascript
const url = 'https://sandbox.xapi.to/v1/sandboxes/33333333-3333-4333-8333-333333333333/files';
const options = {
  method: 'POST',
  headers: {'XAPI-Key': '<apiKey>', 'Content-Type': 'application/json'},
  body: '{"path":"input.txt","content":"Hello from the xAPI Sandbox API Explorer.","encoding":"utf8"}'
};

try {
  const response = await fetch(url, options);
  const data = await response.json();
  console.log(data);
} catch (error) {
  console.error(error);
}
```

```go
package main

import (
	"fmt"
	"strings"
	"net/http"
	"io"
)

func main() {

	url := "https://sandbox.xapi.to/v1/sandboxes/33333333-3333-4333-8333-333333333333/files"

	payload := strings.NewReader("{\n  \"path\": \"input.txt\",\n  \"content\": \"Hello from the xAPI Sandbox API Explorer.\",\n  \"encoding\": \"utf8\"\n}")

	req, _ := http.NewRequest("POST", url, payload)

	req.Header.Add("XAPI-Key", "<apiKey>")
	req.Header.Add("Content-Type", "application/json")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := io.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println(string(body))

}
```

```ruby
require 'uri'
require 'net/http'

url = URI("https://sandbox.xapi.to/v1/sandboxes/33333333-3333-4333-8333-333333333333/files")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Post.new(url)
request["XAPI-Key"] = '<apiKey>'
request["Content-Type"] = 'application/json'
request.body = "{\n  \"path\": \"input.txt\",\n  \"content\": \"Hello from the xAPI Sandbox API Explorer.\",\n  \"encoding\": \"utf8\"\n}"

response = http.request(request)
puts response.read_body
```

```java
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("https://sandbox.xapi.to/v1/sandboxes/33333333-3333-4333-8333-333333333333/files")
  .header("XAPI-Key", "<apiKey>")
  .header("Content-Type", "application/json")
  .body("{\n  \"path\": \"input.txt\",\n  \"content\": \"Hello from the xAPI Sandbox API Explorer.\",\n  \"encoding\": \"utf8\"\n}")
  .asString();
```

```php
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://sandbox.xapi.to/v1/sandboxes/33333333-3333-4333-8333-333333333333/files', [
  'body' => '{
  "path": "input.txt",
  "content": "Hello from the xAPI Sandbox API Explorer.",
  "encoding": "utf8"
}',
  'headers' => [
    'Content-Type' => 'application/json',
    'XAPI-Key' => '<apiKey>',
  ],
]);

echo $response->getBody();
```

```csharp
using RestSharp;

var client = new RestClient("https://sandbox.xapi.to/v1/sandboxes/33333333-3333-4333-8333-333333333333/files");
var request = new RestRequest(Method.POST);
request.AddHeader("XAPI-Key", "<apiKey>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"path\": \"input.txt\",\n  \"content\": \"Hello from the xAPI Sandbox API Explorer.\",\n  \"encoding\": \"utf8\"\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift
import Foundation

let headers = [
  "XAPI-Key": "<apiKey>",
  "Content-Type": "application/json"
]
let parameters = [
  "path": "input.txt",
  "content": "Hello from the xAPI Sandbox API Explorer.",
  "encoding": "utf8"
] as [String : Any]

let postData = JSONSerialization.data(withJSONObject: parameters, options: [])

let request = NSMutableURLRequest(url: NSURL(string: "https://sandbox.xapi.to/v1/sandboxes/33333333-3333-4333-8333-333333333333/files")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error as Any)
  } else {
    let httpResponse = response as? HTTPURLResponse
    print(httpResponse)
  }
})

dataTask.resume()
```