API / stream-download-files-api-content

API

Stream-download Files API content to disk

Stream-download Files API content to disk

GET https://api.x.ai/v1/files/{id}/content streams the raw bytes. Max file size is 512 MB, so prefer writing chunks to disk instead of holding the whole payload in memory. List and delete live in List, download, and delete Files API uploads.

OpenAI SDK

client.files.content(...).write_to_file(...) streams straight to a path:

import os
from openai import OpenAI

client = OpenAI(
    api_key=os.getenv("XAI_API_KEY"),
    base_url="https://api.x.ai/v1",
)

client.files.content("file-abc123").write_to_file("downloaded.pdf")

requests (chunked)

import os
import requests

file_id = "file-abc123"
url = f"https://api.x.ai/v1/files/{file_id}/content"
headers = {"Authorization": f"Bearer {os.getenv('XAI_API_KEY')}"}

with requests.get(url, headers=headers, stream=True) as response:
    response.raise_for_status()
    with open("downloaded.pdf", "wb") as f:
        for chunk in response.iter_content(chunk_size=1024 * 1024):
            if chunk:
                f.write(chunk)

xAI SDK

client.files.content(file_id) returns the full bytes object. Fine for small files; for large ones use requests streaming or the OpenAI client's write_to_file.

import os
from xai_sdk import Client

client = Client(api_key=os.getenv("XAI_API_KEY"))
content = client.files.content("file-abc123")
with open("downloaded.pdf", "wb") as f:
    f.write(content)
print(f"Saved {len(content)} bytes")

curl

curl https://api.x.ai/v1/files/file-abc123/content \
  -H "Authorization: Bearer $XAI_API_KEY" \
  --output downloaded.pdf

After a TTL expires, content returns not found. See Set a TTL on Files API uploads.

Pitfalls

  • Buffering a near-512 MB response into a single bytes object on a small machine.
  • Reusing an expired or deleted file_id after TTL or manual delete.
  • Confusing Collections' 100 MB document cap with the Files API 512 MB limit.
  • Console API credits are a separate bill from SuperGrok's weekly pool on grok.com.