Claude Vision, PDFs and the Files API in Python
👋 In plain words: Claude can read images and PDFs as well as text. You send them as special content blocks, either inline or by uploading the file once and reusing its ID. This lesson walks through each way, step by step, using a test screenshot and a PDF test report.
QA work is full of non-text input: failure screenshots, PDF test reports, scanned requirement documents. In this lesson you will send an image and a PDF to Claude from Python, upload a file once with the Files API and reuse it, learn the limits, and fix the four ingestion mistakes behind most “Claude can’t read my file” bugs.
🔑 Key terms
- Vision: Claude’s ability to read images, such as screenshots, charts and photos.
- Base64: a way to encode binary data (an image, a PDF) as plain text so it can travel in JSON.
- Media type (MIME type): a label for the file format, such as
image/pngorapplication/pdf. - Document block: a content block of type
documentfor PDFs and text documents. - File ID: the ID the Files API returns after an upload, used to reference the file in later requests.
🪜 The steps at a glance
- Prepare a test screenshot.
- Send it as a base64 image block.
- Send a PDF as a document block.
- Upload once with the Files API and reuse the file ID.
- Learn the limits and choose the right method.
- Fix the common ingestion bugs.
🪜 Step 1: Prepare a test image
Normally you would use a real failure screenshot from Playwright or Selenium. To keep this lesson self-contained, the script below draws a tiny PNG with Python’s standard library: a red “error banner” on a white page.
📄 make_png.py
import struct
import zlib
def png(width: int, height: int, pixel) -> bytes:
rows = b"".join(b"\x00" + b"".join(bytes(pixel(x, y)) for x in range(width)) for y in range(height))
def chunk(tag, data):
return struct.pack(">I", len(data)) + tag + data + struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF)
header = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)
return b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", header) + chunk(b"IDAT", zlib.compress(rows)) + chunk(b"IEND", b"")
# white page with a red banner across the top
image = png(120, 80, lambda x, y: (220, 38, 38) if y < 16 else (255, 255, 255))
with open("failure.png", "wb") as f:
f.write(image)
print("wrote failure.png,", len(image), "bytes")⌨️ Terminal
python make_png.py🖥️ Output
wrote failure.png, 259 bytes
🪜 Step 2: Send the image as a base64 block
Put the image before your question in the content list, and set the correct media_type:
📄 vision.py
import base64
import anthropic
client = anthropic.Anthropic()
with open("failure.png", "rb") as f:
image_b64 = base64.standard_b64encode(f.read()).decode("utf-8")
response = client.messages.create(
model="claude-opus-5-5",
max_tokens=500,
messages=[{
"role": "user",
"content": [
{"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": image_b64}},
{"type": "text", "text": "This is a screenshot from a failed UI test. Describe what the page shows."},
],
}],
)
print(response.content[0].text)⌨️ Terminal
python vision.py🖥️ Output (sample run)
The page is mostly blank white with a solid red banner across the top, which usually indicates an error message area, but the banner contains no readable text.
base64.standard_b64encode(...).decode("utf-8")gives one continuous string with no line breaks, which is what the API expects.- You can also send
{"type": "url", "url": "https://..."}as the source when the image is on a public URL.
🪜 Step 3: Send a PDF as a document block
PDFs use a document block with media_type: "application/pdf". Claude reads the text and, on supported models, the page images too. Here we build a one-page PDF test report with the standard library so the example runs anywhere:
📄 make_pdf.py
def make_pdf(lines: list[str]) -> bytes:
text = "BT /F1 12 Tf 50 780 Td 16 TL " + " ".join(f"({l}) Tj T*" for l in lines) + " ET"
objs = [
"<< /Type /Catalog /Pages 2 0 R >>",
"<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 595 842] /Resources << /Font << /F1 5 0 R >> >> /Contents 4 0 R >>",
f"<< /Length {len(text)} >>\nstream\n{text}\nendstream",
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",
]
out, offsets = "%PDF-1.4\n", []
for i, body in enumerate(objs, 1):
offsets.append(len(out))
out += f"{i} 0 obj\n{body}\nendobj\n"
xref = len(out)
out += f"xref\n0 {len(objs) + 1}\n0000000000 65535 f \n" + "".join(f"{o:010d} 00000 n \n" for o in offsets)
out += f"trailer\n<< /Size {len(objs) + 1} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF"
return out.encode("latin-1")
report = make_pdf(["Nightly regression report", "Passed: 482 Failed: 3 Skipped: 7",
"FAILED test_checkout_total", "FAILED test_login_lockout", "FAILED test_export_csv"])
open("report.pdf", "wb").write(report)
print("wrote report.pdf,", len(report), "bytes")⌨️ Terminal
python make_pdf.py🖥️ Output
wrote report.pdf, 752 bytes
📄 pdf_input.py
import base64
import anthropic
client = anthropic.Anthropic()
pdf_b64 = base64.standard_b64encode(open("report.pdf", "rb").read()).decode("utf-8")
response = client.messages.create(
model="claude-opus-5-5",
max_tokens=500,
messages=[{
"role": "user",
"content": [
{"type": "document", "source": {"type": "base64", "media_type": "application/pdf", "data": pdf_b64}},
{"type": "text", "text": "List the failed tests and the pass rate."},
],
}],
)
print(response.content[0].text)⌨️ Terminal
python pdf_input.py🖥️ Output (sample run)
Failed tests: test_checkout_total, test_login_lockout, test_export_csv. Pass rate: 482 of 485 executed tests passed (99.4%), with 7 skipped.
🪜 Step 4: Upload once with the Files API
If you ask several questions about the same file, or use it in a batch, upload it once and reference its file_id. The Files API is out of beta: use client.files with no beta header.
📄 files_api.py
from pathlib import Path
import anthropic
client = anthropic.Anthropic()
uploaded = client.files.upload(file=("report.pdf", Path("report.pdf").read_bytes(), "application/pdf"))
print("file id:", uploaded.id)
for question in ["How many tests failed?", "Which failed test touches money?"]:
response = client.messages.create(
model="claude-opus-5-5",
max_tokens=300,
messages=[{
"role": "user",
"content": [
{"type": "document", "source": {"type": "file", "file_id": uploaded.id}},
{"type": "text", "text": question},
],
}],
)
print(f"Q: {question}\nA: {response.content[0].text}")⌨️ Terminal
python files_api.py🖥️ Output (sample run)
file id: file_01t5Qgh2Yhanbn4nC8cLPXhG
Q: How many tests failed?
A: 3 tests failed.
Q: Which failed test touches money?
A: test_checkout_total, because it checks the order total customers pay.
- Upload, list and delete operations are free. The file’s content is billed as input tokens each time you use it in a message.
- Files stay until you delete them (
client.files.delete(file_id)). Clean up files you no longer need. - The block type must match the file: a PDF or text file is a
documentblock, an image is animageblock.
🪜 Step 5: Know the limits and choose a method
| Base64 inline | Files API (file_id) |
|
|---|---|---|
| Best for | One-off requests | The same file used many times, batches |
| Request size | Counts toward the 32 MB request limit | File up to 500 MB; reference is tiny |
| Storage | None | Up to 100 GB per organisation, kept until deleted |
| Platforms | All | Not available on Amazon Bedrock or Google Vertex AI |
PDF limits from Anthropic’s documentation: up to 32 MB per request and 600 pages (100 pages for models with a 200K context window). Large PDFs also use many tokens, so count them first (Lesson 5).
🪜 Step 6: Fix the common ingestion bugs
The exam’s “Integration Resilience” skill includes faulty multi-format ingestion through the Files API. These four defects cause most failures:
- Wrong media type. Sending a JPEG with
media_type: "image/png", or a PDF astext/plain. Detect the type from the file’s bytes or extension, and map it explicitly. - Wrong block type for the file. Referencing an uploaded PNG in a
documentblock, or a PDF in animageblock. Choose the block from the file’s MIME type. - Broken base64. Using
base64.encodebytes(which inserts line breaks) or forgetting.decode(). Usestandard_b64encode(...).decode("utf-8"). - Using the Files API where it does not exist. Code that works on the first-party API fails on Bedrock or Vertex. Fall back to inline base64 there.
This helper applies rules 1 and 2. It runs locally without calling Claude:
📄 ingest.py
from pathlib import Path
TYPES = {
".png": ("image", "image/png"),
".jpg": ("image", "image/jpeg"),
".jpeg": ("image", "image/jpeg"),
".gif": ("image", "image/gif"),
".webp": ("image", "image/webp"),
".pdf": ("document", "application/pdf"),
".txt": ("document", "text/plain"),
}
def block_for_upload(path: str, file_id: str) -> dict:
ext = Path(path).suffix.lower()
if ext not in TYPES:
raise ValueError(f"unsupported file type: {ext}")
block_type, _media = TYPES[ext]
return {"type": block_type, "source": {"type": "file", "file_id": file_id}}
for name in ["failure.png", "report.pdf", "notes.txt", "video.mp4"]:
try:
print(f"{name:<12} ->", block_for_upload(name, "file_011example"))
except ValueError as e:
print(f"{name:<12} -> rejected: {e}")⌨️ Terminal
python ingest.py🖥️ Output
failure.png -> {'type': 'image', 'source': {'type': 'file', 'file_id': 'file_011example'}}
report.pdf -> {'type': 'document', 'source': {'type': 'file', 'file_id': 'file_011example'}}
notes.txt -> {'type': 'document', 'source': {'type': 'file', 'file_id': 'file_011example'}}
video.mp4 -> rejected: unsupported file type: .mp4
🌍 Real-world example: Ravi’s screenshot pipeline
Ravi’s tool sent every failure screenshot with media_type: "image/png". One project saved screenshots as JPEG, and those requests failed with a 400 error. He switched to the mapping above, added a pytest test for each extension, and the failures stopped.
🧪 Practice Questions
Question 1. A service uploads a PNG screenshot with the Files API and references it in a document content block. Requests fail. What is the defect?
- A. The file is too small
- B. The block type does not match the file type: images must use an image block
- C. The Files API needs a beta header
- D. PNG is not supported
Show answer
Answer: B. The content-block type must match the file’s MIME type. PDFs and text use document blocks; images use image blocks.
Question 2. A team asks 40 questions about the same 30 MB PDF. What is the best approach?
- A. Send the PDF as base64 in all 40 requests
- B. Upload it once with the Files API and reference the file_id
- C. Split it into images
- D. Paste the PDF text into the system prompt of each request
Show answer
Answer: B. Uploading once avoids resending a large payload every time and keeps requests small. The content is still billed as input tokens when used.
Question 3. Code that uses the Files API works against the Claude API but fails on Google Vertex AI. Why?
- A. Vertex AI does not support PDFs
- B. The Files API is not available on Vertex AI or Amazon Bedrock
- C. Vertex AI needs a different model ID format only
- D. File IDs expire after one minute
Show answer
Answer: B. The Files API is a first-party feature. On Bedrock and Vertex, send files inline as base64.
Question 4. Which two encodings produce a valid base64 image payload for the API? (Choose 2.)
- A. base64.standard_b64encode(data).decode(“utf-8”)
- B. base64.encodebytes(data) without decoding
- C. base64.b64encode(data).decode(“ascii”)
- D. str(data)
Show answer
Answer: A and C. The API needs a continuous base64 string. encodebytes inserts newlines and returns bytes; str(data) is not base64 at all.
📝 Assignment
- Task 1: Send a real failure screenshot from one of your UI tests to Claude with the assertion message and ask for the likely cause.
✅ Done when: Claude’s answer refers to something visible in the screenshot. - Task 2: Write pytest tests for
block_for_uploadcovering every supported extension and one unsupported one.
✅ Done when: all tests pass and the unsupported case raisesValueError. - Stretch: Write a script that uploads every PDF in a folder, asks one question about each, saves the answers to a CSV, and deletes the uploaded files at the end.
✅ Done when: the CSV has one row per PDF andclient.files.list()shows none of them afterwards.
❓ Frequently Asked Questions
🤔 Can Claude read screenshots?
Yes. Send them as image blocks (base64 or URL). Claude can describe layouts, read visible text and compare what it sees with the expected result.
🤔 How do I send a PDF to Claude in Python?
Use a document block with media_type: "application/pdf", either as base64 data or as a file_id from the Files API.
🤔 Does the Files API need a beta header?
Not any more. It is out of beta; use client.files.upload() in current SDKs.
🤔 What is the maximum PDF size for Claude?
Anthropic documents 32 MB per request and 600 pages (100 pages for 200K-context models). Uploaded files can be up to 500 MB.
🏁 Summary
- Images use
imageblocks, PDFs and text usedocumentblocks; put them before your question. - Base64 must be one continuous string with the correct
media_type. - Upload large or reused files once with
client.files.upload()and reference thefile_id. - The Files API is not on Bedrock or Vertex; use inline base64 there.
- Map file type to block type and media type explicitly, and test the mapping.
Next, continue with Claude API Error Handling: 429, 529, Timeouts, Retries and Fallback.
Independent study material by SQA Tools. Not affiliated with, endorsed by or sponsored by Anthropic. Claude is a trademark of Anthropic. Practice questions are original, not real exam content. Code outputs marked “sample run” come from running the exact code against a local stand-in for the Claude API, so real replies, IDs and token counts will differ. Exam facts checked against Anthropic’s official CCDV-F exam guide v1.1 on 24 Nov 2026.