Claude Files API Python Example

Use the Anthropic Files API in Python to upload documents once and reference them in multiple Claude requests. Reduces costs by avoiding repeated base64 encoding of large files.

💥 50p impulse-buy: Power Prompts PDF (first 10 buyers) 30 battle-tested Claude Code prompts · 8-page PDF · paste into CLAUDE.md and never re-type a prompt again · 50p impulse-buy, no commitment

The Anthropic Files API lets you upload a document once and reference it across many Claude requests using a file_id. This is especially useful for document Q&A apps, code review tools, or any workflow that processes the same file repeatedly.

Installation

pip install anthropic  # Files API included in SDK ≥ 0.34

Upload a file

import anthropic

client = anthropic.Anthropic()  # reads ANTHROPIC_API_KEY from env

# Upload a PDF
with open("quarterly_report.pdf", "rb") as f:
    file_obj = client.beta.files.upload(
        file=("quarterly_report.pdf", f, "application/pdf"),
    )

file_id = file_obj.id
print(f"Uploaded: {file_id}")
# file_id: file_01ABC123...

Reference the file in a Claude request

response = client.beta.messages.create(
    model="claude-sonnet-4-6",
    max_tokens=1024,
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "document",
                    "source": {
                        "type": "file",
                        "file_id": file_id,
                    }
                },
                {
                    "type": "text",
                    "text": "Summarize the key financial highlights from this report in 5 bullet points."
                }
            ]
        }
    ],
    betas=["files-api-2025-04-14"],
)

print(response.content[0].text)

Reuse the same file across multiple requests

questions = [
    "What was the revenue growth year-over-year?",
    "Which product line had the highest margin?",
    "What risks did management highlight?",
]

for question in questions:
    resp = client.beta.messages.create(
        model="claude-sonnet-4-6",
        max_tokens=512,
        messages=[
            {
                "role": "user",
                "content": [
                    {"type": "document", "source": {"type": "file", "file_id": file_id}},
                    {"type": "text", "text": question}
                ]
            }
        ],
        betas=["files-api-2025-04-14"],
    )
    print(f"Q: {question}")
    print(f"A: {resp.content[0].text}\n")

List uploaded files

files = client.beta.files.list()
for f in files.data:
    print(f.id, f.filename, f.size, f.created_at)

Delete a file when done

client.beta.files.delete(file_id)
print("File deleted")

Upload an image file

with open("diagram.png", "rb") as f:
    img_file = client.beta.files.upload(
        file=("diagram.png", f, "image/png"),
    )

response = client.beta.messages.create(
    model="claude-sonnet-4-6",
    max_tokens=512,
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "image",
                    "source": {
                        "type": "file",
                        "file_id": img_file.id,
                    }
                },
                {"type": "text", "text": "Describe the architecture shown in this diagram."}
            ]
        }
    ],
    betas=["files-api-2025-04-14"],
)

Files API vs base64 inline — when to use each

ScenarioRecommendationReason
Same file queried 2+ timesFiles APIUpload once; reference is lightweight
One-off file, never reusedBase64 inlineNo upload RTT overhead
File > 1 MBFiles APIAvoids large base64 payload in every request
File generated at runtimeBase64 inlineNo need to manage file lifecycle
Document Q&A across many usersFiles APIUpload once, all users share same file_id
Privacy-sensitive single-use docBase64 inlineAvoids data persisting on Anthropic servers

Supported file types

TypeMIME typesMax size
PDFapplication/pdf32 MB
Plain texttext/plain32 MB
Imagesimage/jpeg, image/png, image/gif, image/webp32 MB

Files are retained for 30 days after last access. For cost estimation across document Q&A workflows, use the Claude API Cost Calculator. For PDF analysis patterns, see the PDF analysis guide and vision API example.

Frequently asked questions

What is the Anthropic Files API?
The Files API (launched 2025) lets you upload a file once — PDF, plain text, image, or code — get back a `file_id`, and reference that ID in multiple Claude requests. This avoids re-uploading and re-encoding the same document on every call, reducing both latency and cost for applications that reprocess the same files repeatedly.
What file types does the Claude Files API support?
PDFs, plain text (.txt), Markdown, most image formats (JPEG, PNG, GIF, WebP), and source code files. The maximum file size per upload is 32 MB. Binary formats like .docx or .xlsx are not directly supported — convert to PDF or extract text first.
Does using the Files API save money on Claude API costs?
Yes, when you reference the same file in multiple requests. Instead of paying input tokens to encode a 100-page PDF as base64 on every call, you upload once and pay only for the tokens in each request's user message. Prompt caching on top of file references reduces costs further for repeated queries against the same document.
How long does the Files API store uploaded files?
Files are stored for 30 days after the last access, then automatically deleted. You can also delete files explicitly with `client.beta.files.delete(file_id)`. There is no charge for storage — only for the input tokens consumed when the file is read during a message request.
Can I use the Files API with tool use or extended thinking?
Yes. File references work the same as any other content block in the `messages` array. You can include a file reference alongside tool results, in multi-turn conversations, or in requests that also enable extended thinking — the file content is injected at the position of the reference block.

Free tools

Cost Calculator → API Cookbook → Diff Summarizer → Skills Browser →

More examples

Claude API Python QuickstartClaude API Node.js / TypeScript QuickstartClaude API Streaming in PythonClaude API Streaming in Node.js / TypeScriptClaude API Tool Use in PythonClaude API Tool Use in Node.js / TypeScript