FILE API · INTEGRATION REFERENCE
File upload API
Upload one file with anonymous x402 and receive a signed download link. By default the link stays valid for 10 days.
Upload one file with one HTTP request and get a signed download link back. The empty POST quote shows the current price; if the service is temporarily unavailable it returns 503 and nothing is charged.
One endpoint, one file
No account, platform API key or quota is used. Do not send an Authorization header or website cookie. One accepted payment belongs to one logical file delivery. Files are downloaded as attachments.
Files must be nonempty. The first version supports up to 10 MiB; a deployment may set a lower limit. The default lifetime is 10 days from successful delivery. The returned expires_at is authoritative; replay never extends it.
POST https://api.koinelix.com/v1/files1. Request and inspect a quote
Send an empty POST without a payment header. Read PAYMENT-REQUIRED and obtain explicit wallet approval for its exact resource, network, asset, atomic amount and recipient. The server never needs your wallet private key or recovery phrase.
# 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. Keep the original materials
Retain the exact file bytes and the original PAYMENT-SIGNATURE securely until the result expires or recovery finishes; they are all a retry needs. An Idempotency-Key header is optional: if you send one, create it once per upload as 32 lowercase hex characters (128 random bits) and reuse it unchanged on every retry. This example assumes an x402 wallet client has produced the payment header after approval; it does not sign anything.
# 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. Upload one multipart file
Send the file as multipart/form-data with exactly one part named file (let curl or FormData set Content-Type and its boundary), or as JSON with the file as base64 (see the JSON form below, up to 8 MiB). Do not send bucket, object key, price or lifetime fields. No request or payment is retried automatically in this example.
# 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 form for small files
# 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"Example with the x402 TypeScript client
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)' : '');Example with the x402 Python client
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())| Field / header | Meaning |
|---|---|
file | Required file part, with its original filename and MIME metadata. Extra parts and empty files are rejected. |
content_base64 | JSON form only: the file as one standard padded Base64 string, up to 8 MiB decoded. Optional filename and content_type fields are the only others accepted. |
PAYMENT-SIGNATURE | Required for paid upload and recovery: the original base64 x402 v2 authorization. |
Idempotency-Key | Optional. If sent with a payment it is 32 lowercase hex characters, created once per upload and reused on every retry. |
Successful delivery and URL
The first completed delivery returns 201. A replay returns 200 with the same file and expiry. The following values are illustrative; the example signature cannot download a file.
{
"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"
}
}| Field / header | Meaning |
|---|---|
file_id | Opaque file identifier. Knowing it does not authorize recovery. |
filename | Normalized original filename. |
content_type | Normalized MIME metadata; it does not establish content safety. |
size_bytes | Actual file size in bytes. |
sha256 | Lowercase SHA-256 of the actual file bytes. |
expires_at | Fixed RFC3339 UTC expiry. |
url | Complete signed GET URL. Use it unchanged, including every query parameter. |
Anyone holding the URL can download until expiry. Keep it out of public logs and analytics. The signature controls access; it does not encrypt content or revoke copies already downloaded. The link works with a plain GET, and HEAD is accepted too. Downloads are attachments, not inline previews. No separate list, lookup or renewal API is provided.
Recover without a new payment
On a timeout, disconnection, 202 or an uncertain error, preserve the original materials. Repeat the same endpoint with X-Koinelix-Recover-Only: true, the original proof and key, and the same file. A changed multipart boundary is allowed; changed normalized metadata or content is not.
202 returns data.file_id and status (payment_pending or storage_pending), not a URL. Respect Retry-After. Recover-Only checks or replays existing work and never starts a new Put. If a new write is still required, explicitly reuse the upload command without that header, preserving the same proof, key and file. Do not use an automatic payment wrapper to replace the authorization after an error.
# 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 means the result or recovery window has expired. There is no renewal or automatic new purchase. A new upload requires a separate, explicit intent and payment approval.
Common errors
Check error.code as well as HTTP status. These are common cases, not an exhaustive list. An error alone does not prove the original payment was unconfirmed.
| HTTP | Error code | Action |
|---|---|---|
| 400 | validation_failed | Correct malformed input; preserve any existing intent materials. |
| 401 | unsupported_authentication | Remove Authorization; this service only accepts anonymous x402. |
| 402 | payment_required | Inspect the quote before wallet approval. |
| 402 | payment_invalid | Check the original authorization and the approved quote. |
| 404 | purchase_not_found | Recover-Only found no matching intent and did not create or pay for one. |
| 408 | request_timeout | Keep the original materials; do not assume no payment. |
| 409 | idempotency_conflict | The key, proof, file or metadata do not match the original intent. |
| 410 | file_expired | The original result expired; replay does not renew it. |
| 410 | upload_retry_expired | The delivery recovery window ended; do not automatically pay again. |
| 413 | file_too_large | The request or file exceeds an accepted limit. |
| 415 | unsupported_media_type | Use multipart/form-data with one file part, or application/json with content_base64. |
| 429 | upload_rate_limited | Wait before retrying with the original materials. |
| 503 | file_service_unavailable | Service or dependency unavailable; keep any existing intent materials. |
Discovery for agents
The upload is listed together with the image services in https://api.koinelix.com/openapi.json, /.well-known/x402 and /agents.md. An agent can read /agents.md for a ready-to-use guide with a TypeScript example. Use this page for the multipart request; do not reuse an image request body.