文件 API · 接入参考

文件上传 API

通过匿名 x402 上传一个文件,成功后直接获得签名下载链接,默认 10 天内有效。

← 平台文档

用一次 HTTP 请求上传一个文件,并在响应中直接拿到签名下载链接。空 POST 报价会给出当前价格;服务暂时不可用时返回 503,不会扣款。

一个入口,一个文件

无需账号、平台 API Key 或额度;不要发送 Authorization 头或网站 Cookie。一笔接受的付款绑定一次逻辑文件交付。文件以附件下载。

文件不能为空。首版硬能力为 10 MiB,部署可配置更低上限;默认从交付成功起保留 10 天。实际期限以返回的 expires_at 为准,重放不延长。

POST https://api.koinelix.com/v1/files

1. 获取并核对报价

不带付款头发送空 POST,读取 PAYMENT-REQUIRED。通过钱包客户端核对准确的 resource、网络、资产合约、最小单位金额和收款方,并明确批准。服务器不需要你的钱包私钥或助记词。

# Inspect the quote before your wallet approves anything.
curl --disable --silent --show-error --include --max-time 120 \
  --request POST 'https://api.koinelix.com/v1/files'
# Expected when available: HTTP 402 + PAYMENT-REQUIRED (base64 x402 v2 quote).
# Check the resource, network, asset, atomic amount and payee in your wallet client.

2. 保存原请求材料

请安全保留原文件字节和原 PAYMENT-SIGNATURE,直到结果到期或恢复结束,重试只需要它们。Idempotency-Key 请求头是可选的:如果发送,请为每次上传生成一次 32 位小写十六进制键(128 位随机),并在该次上传的所有重试中原样复用。示例假设 x402 钱包客户端已在批准后生成付款头,本页不签名。

# Run ONCE for a new upload, before approving its payment.
IDEMPOTENCY_KEY="$(openssl rand -hex 16)"
# Securely keep this key, the original PAYMENT-SIGNATURE and the exact file until recovery ends.
# Never run this line again to recover an upload.

3. 上传单个 multipart 文件

用 multipart/form-data 只发送一个名为 file 的文件 part(让 curl 或 FormData 设置 Content-Type 与 boundary),或者用 JSON 把文件放进 base64(见下方 JSON 写法,最大 8 MiB)。不要发送桶、对象 key、售价或期限字段。示例不会自动重试请求或付款。

# Set FILE_PATH to the original file. Your x402 wallet client supplies PAYMENT_SIGNATURE.
# Keep the original key and signature. Do not sign or generate a new key for recovery.
: "${FILE_PATH:?Set FILE_PATH to the original file}"
: "${PAYMENT_SIGNATURE:?Use the original wallet-approved PAYMENT-SIGNATURE}"
: "${IDEMPOTENCY_KEY:?Use the saved 32-lowercase-hex key}"
umask 077
OUTPUT_DIR="$(mktemp -d)"
# Keep proof/key out of process arguments; this new directory is private.
printf '%s\n' "PAYMENT-SIGNATURE: $PAYMENT_SIGNATURE" "Idempotency-Key: $IDEMPOTENCY_KEY" > "$OUTPUT_DIR/request.headers"
curl --disable --silent --show-error --max-time 120 \
  --request POST 'https://api.koinelix.com/v1/files' \
  --header "@$OUTPUT_DIR/request.headers" \
  --form "file=@$FILE_PATH" \
  --dump-header "$OUTPUT_DIR/response.headers" \
  --output "$OUTPUT_DIR/response.json" \
  --write-out 'HTTP %{http_code}\n'
printf 'Response saved in %s\n' "$OUTPUT_DIR"
# Read response.json locally. Its data.url is a temporary download capability.
# A timeout, 202 or error is not permission to approve another payment.

小文件的 JSON 写法

# JSON form, up to 8 MiB. Use the same PAYMENT-SIGNATURE and Idempotency-Key (if you send one) on every retry.
: "${FILE_PATH:?Set FILE_PATH to the original file}"
: "${PAYMENT_SIGNATURE:?Use the wallet-approved PAYMENT-SIGNATURE}"
umask 077
BODY="$(mktemp)"
# Standard padded Base64 on one line, placed in the JSON body.
printf '{"filename":"%s","content_base64":"%s"}' "$(basename "$FILE_PATH")" "$(base64 < "$FILE_PATH" | tr -d '\n')" > "$BODY"
curl --disable --silent --show-error --max-time 120 \
  --request POST 'https://api.koinelix.com/v1/files' \
  --header "PAYMENT-SIGNATURE: $PAYMENT_SIGNATURE" \
  --header 'Content-Type: application/json' \
  --data-binary "@$BODY"
rm -f "$BODY"

使用 x402 TypeScript 客户端的示例

npm install @x402/fetch @x402/evm viem
// Run as an ES module, for example: save as upload.mts and run "npx tsx upload.mts".
// Running this example makes a paid call. Review the quote with curl first.
import { wrapFetchWithPaymentFromConfig } from '@x402/fetch';
import { ExactEvmScheme } from '@x402/evm';
import { privateKeyToAccount } from 'viem/accounts';
import { openAsBlob } from 'node:fs';
import { randomBytes } from 'node:crypto';

// A wallet that holds USDC on Base. Keep the key in an environment variable.
const account = privateKeyToAccount(process.env.WALLET_PRIVATE_KEY as `0x${string}`);

// Remember the exact signature the library sends: a retry after a lost response must reuse it.
let paymentSignature = '';
const recordingFetch: typeof fetch = (input, init) => {
  const signature = new Headers(input instanceof Request ? input.headers : init?.headers).get('PAYMENT-SIGNATURE');
  if (signature) paymentSignature = signature;
  return fetch(input, init);
};
const fetchWithPayment = wrapFetchWithPaymentFromConfig(recordingFetch, {
  schemes: [{ network: 'eip155:8453', client: new ExactEvmScheme(account) }],
});

// Create the key once per upload and keep it together with the signature and the file.
const idempotencyKey = randomBytes(16).toString('hex');
const file = await openAsBlob(process.env.FILE_PATH!); // a Blob can be resent; a stream cannot
const form = new FormData();
form.append('file', file, 'upload.bin'); // exactly one part named "file"

const response = await fetchWithPayment('https://api.koinelix.com/v1/files', {
  method: 'POST',
  headers: { 'Idempotency-Key': idempotencyKey },
  body: form,
});
// 201 = done. 202 = still being completed: wait Retry-After, then resend the SAME request with the
// saved PAYMENT-SIGNATURE and Idempotency-Key (plain fetch, no new payment). Never pay again.
if (!response.ok && response.status !== 202) throw new Error(`HTTP ${response.status}: ${await response.text()}`);
const { data } = await response.json();
console.log(response.status, data?.url, paymentSignature ? '(signature saved)' : '');

使用 x402 Python 客户端的示例

pip install "x402[httpx,evm]"
import asyncio
import os
import secrets

from eth_account import Account
from x402 import x402Client
from x402.http.clients import x402HttpxClient
from x402.mechanisms.evm import EthAccountSigner
from x402.mechanisms.evm.exact import register_exact_evm_client

URL = "https://api.koinelix.com/v1/files"


async def main():
    # A wallet that holds USDC on Base. Keep the key in an environment variable.
    account = Account.from_key(os.environ["WALLET_PRIVATE_KEY"])
    client = x402Client()
    register_exact_evm_client(client, EthAccountSigner(account), networks="eip155:8453")

    # Create the key once per upload; keep it with the file and the payment signature.
    idempotency_key = secrets.token_hex(16)
    path = os.environ["FILE_PATH"]
    with open(path, "rb") as handle:
        content = handle.read()  # bytes, so the library can resend the identical body

    async with x402HttpxClient(client, timeout=300) as http:
        response = await http.post(
            URL,
            headers={"Idempotency-Key": idempotency_key},
            files={"file": (os.path.basename(path), content)},  # exactly one part named "file"
        )
    if response.status_code == 202:
        # Still being completed: wait Retry-After, then resend the SAME request with the SAME
        # PAYMENT-SIGNATURE and Idempotency-Key. Never pay again.
        raise SystemExit("202: retry the identical request after " + response.headers.get("Retry-After", "5") + "s")
    response.raise_for_status()
    print(response.json()["data"]["url"])  # plain GET download link


asyncio.run(main())
字段 / 请求头含义
file必填文件 part,保留原文件名与 MIME 元数据;额外 part、空文件会被拒绝。
content_base64仅 JSON 写法:文件内容为一个标准带填充的 Base64 字符串,解码后最大 8 MiB;只允许另带可选的 filename、content_type。
PAYMENT-SIGNATURE付款上传和恢复必填:原 base64 编码的 x402 v2 授权。
Idempotency-Key可选。随付款发送时为 32 位小写十六进制键,每次上传生成一次,并在所有重试中复用。

交付成功与访问地址

首次完成交付返回 201;重放返回 200,仍为原文件及原期限。以下值仅为示意,示例签名不能用于下载。

{
  "data": {
    "file_id": "file_0123456789abcdef0123456789abcdef",
    "filename": "example.bin",
    "content_type": "application/octet-stream",
    "size_bytes": 1234,
    "sha256": "0000000000000000000000000000000000000000000000000000000000000000",
    "expires_at": "2026-11-05T00:00:00Z",
    "url": "https://koinelix.com/oss/bucket-us-test/files/file_0123456789abcdef0123456789abcdef?AWSAccessKeyId=EXAMPLE_READER&Expires=1793836800&Signature=EXAMPLE_NOT_VALID"
  }
}
字段 / 请求头含义
file_id不透明文件标识;知道它不代表有恢复权限。
filename规范化的原文件名。
content_type规范化的 MIME 元数据,不证明内容安全。
size_bytes实际文件字节数。
sha256实际文件字节的小写 SHA-256 摘要。
expires_at固定的 RFC3339 UTC 到期时间。
url完整的签名 GET 地址,连同全部查询参数原样使用。

持有地址的任何人都可在到期前下载,不要放入公开日志或分析上报。签名用于访问控制,不加密内容,也不能撤回已经下载的副本。该地址可直接 GET 下载,也支持 HEAD;下载强制附件,不提供内联预览。没有独立列表、查询或续签接口。

不新增付款的恢复

超时、断线、202 或错误导致结果未知时保留原材料,在同一接口携 X-Koinelix-Recover-Only: true、原证明、原键和同文件核对。允许 multipart boundary 改变,不允许改变规范化后的元数据或内容。

202 只返回 data.file_id 与 status(payment_pending 或 storage_pending),没有下载地址。遵守 Retry-After;Recover-Only 仅核对或重放已有工作,不发起新的 Put。仍需新写入时,明确使用不带该头的原上传命令,继续复用同一证明、键和文件。不要让自动付款包装器在错误后替换授权。

# Set FILE_PATH to the original file. Your x402 wallet client supplies PAYMENT_SIGNATURE.
# Keep the original key and signature. Do not sign or generate a new key for recovery.
: "${FILE_PATH:?Set FILE_PATH to the original file}"
: "${PAYMENT_SIGNATURE:?Use the original wallet-approved PAYMENT-SIGNATURE}"
: "${IDEMPOTENCY_KEY:?Use the saved 32-lowercase-hex key}"
umask 077
OUTPUT_DIR="$(mktemp -d)"
# Keep proof/key out of process arguments; this new directory is private.
printf '%s\n' "PAYMENT-SIGNATURE: $PAYMENT_SIGNATURE" "Idempotency-Key: $IDEMPOTENCY_KEY" > "$OUTPUT_DIR/request.headers"
curl --disable --silent --show-error --max-time 120 \
  --request POST 'https://api.koinelix.com/v1/files' \
  --header "@$OUTPUT_DIR/request.headers" \
  --header "X-Koinelix-Recover-Only: true" \
  --form "file=@$FILE_PATH" \
  --dump-header "$OUTPUT_DIR/response.headers" \
  --output "$OUTPUT_DIR/response.json" \
  --write-out 'HTTP %{http_code}\n'
printf 'Response saved in %s\n' "$OUTPUT_DIR"
# Read response.json locally. Its data.url is a temporary download capability.
# A timeout, 202 or error is not permission to approve another payment.

410 表示结果或交付恢复窗口已到期,不会续期或自动新购。再次上传须作为独立意图并重新明确批准付款。

常见错误

同时检查 error.code 和 HTTP 状态;下列是常见情况,并非完整清单。不能仅凭错误判定原付款未确认。

HTTP 状态错误码处理
400validation_failed修正输入格式,保留任何已存在的意图材料。
401unsupported_authentication移除 Authorization;本服务只接受匿名 x402。
402payment_required钱包批准前先核对报价。
402payment_invalid核对原授权与已批准报价。
404purchase_not_foundRecover-Only 未找到匹配意图,未创建或支付新意图。
408request_timeout保留原材料,不能据此假定未付款。
409idempotency_conflict键、证明、文件或元数据与原意图不一致。
410file_expired原结果已到期,重放不续期。
410upload_retry_expired交付恢复窗口已结束,不自动再次付款。
413file_too_large请求或文件超过允许上限。
415unsupported_media_type使用只含一个 file part 的 multipart/form-data,或带 content_base64 的 application/json。
429upload_rate_limited等待后携原材料重试。
503file_service_unavailable服务或依赖不可用,保留任何已存在的意图材料。

面向 Agent 的发现文档

文件上传与图片服务一起列在 https://api.koinelix.com/openapi.json、/.well-known/x402 和 /agents.md 中。Agent 可以读取 /agents.md,里面有可直接使用的说明和 TypeScript 示例。本页给出 multipart 请求的写法,不要复用图片请求正文。