Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Claude
  • CLAUDE.md, settings.json and Plugins: Which Claude Code File Advises, Which Enforces, Which Packages
  • Authoring a Claude Skill: SKILL.md, Frontmatter, Progressive Disclosure and the Description That Triggers It
  • One Change, Four Environments: Where a Claude Config Edit Lands in Dev, Staging, Prod and CI
  • Claude in the SDLC: Prompts in Git, a Change Gate by Path, a Claude Review That Advises and a Person Who Merges
  • Hooks That Block Destructive Actions: a PreToolUse Gate That Allows, Asks or Denies
  • Choosing a Claude Code Extension: Skill, Hook, Rules File, Subagent, Slash Command or Plugin
  • Rolling Out Claude Code to a Team: Settings Precedence, dontAsk in CI, a Hook for Every-Time Rules and a Plugin for Five Repos
  • A Claude Code Review Bot in CI: Headless -p, JSON Findings, Team Rules in Git and a Person on the Merge
  • Lab: Three Planted Bugs in a Claude Code CI Repo, a Permission Mode, a Plugin Path and an MCP Token Variable
  • Configuring MCP Servers in Claude Code: A Command or a URL, Three Scopes, and Three Moves When One Breaks
  • The Claude Messages API: Your First Call, Field by Field
  • Claude Tool Use: How tool_use and tool_result Work in the Messages API
  • Claude Client SDKs Wrap One REST API: Raw HTTP, Python, TypeScript and Async Calls Compared
  • Anthropic SDK Timeouts, Retries and Error Classes: Configure the Client Once, Then Give 429, 529, 400 and Timeouts Their Own Move
  • Claude Streaming Events: The Event Order, message_stop, Tool Arguments, Stop Reasons and a WebSocket Relay
  • Images, PDFs and Thinking Blocks in the Claude Messages API: Typed Blocks In, Typed Blocks Out
  • Getting Data Into Claude: PDF Documents, the Files API, Search Results and Citations
  • Opus, Sonnet or Haiku: Pick the Claude Model per Job, and Test the Request When a New Release Arrives
  • Adaptive Thinking and Effort in Claude: Two Dials, Set per Workload, and the Thinking Block You Must Pass Back
  • Claude Cost Tracking From usage: Count Before, Cap During, Read After, Then Find the Line That Drives the Bill
  • Claude Cache Breakpoints: Where to Put cache_control, How to Move It With the Chat, and Why the Reads Stay at Zero
  • Claude Message Batches or Real Time: Choose by Who Is Waiting, Match by custom_id, Resend Only the Failures
  • Calling Claude Through Amazon Bedrock, Google Cloud and Microsoft Foundry: Same Call, Different Door
  • The Life Cycle of a Claude App: Six Phases, a Model That Retires, and a Release Gate for Every Change
  • Pinning Claude Model IDs and Upgrading Safely: One Change at a Time, a Golden-Set Replay and a Staged Rollout
  • Content Boundaries and Schema Design for Claude: Fence the Input in a Tag, Let the Output Say I Don't Know
  • The Agentic Loop and stop_reason: Keep Turning on tool_use, Stop on end_turn, Cap the Turns
  • The Claude Agent SDK: query(), ClaudeAgentOptions and @tool, in Python and TypeScript
  • Fix the Agent: Four Broken Claude Agent SDK Configs, From the Symptom to the One Wrong Line
  • Claude Managed Agents: Cloud Sandbox, Self-Hosted Sandbox or Self-Hosted Service
  • Agent SDK Hooks for Deterministic Actions: PreToolUse, PostToolUse, and Four Hooks That Fail Silently
  • Memory and Context-Window Patterns for Claude Agents: Context Editing, Compaction and the Memory Tool
  • Reading an Agent Trace: Five Signatures, Five Missing Patterns, and How Long a Fact Must Live
  • Tool Descriptions for Claude: How Claude Picks a Tool, and How to Stop It Picking the Wrong One
  • Tool Input Schemas and Error Responses for Claude: Required Fields, Enums, is_error and a Retry Flag
  • Tool Response Shaping and a Lean Tool Set: Give Claude a Sticky Note, Not the Filing Cabinet
  • Fix the Tool Schema: Read the Trace, Fix the Card, Re-Run (Four Real Schema Bugs)
  • Client Tools, Server Tools and Approval Gates: Who Runs the Tool, and Who Says Yes First
  • Built-in Tool, Custom Tool, Skill or MCP Server? Pick the Lightest One That Fits
  • System Prompt or User Turn: Where Each Instruction Goes, and Output Limits Your Code Enforces
  • Refine the Prompt One Line at a Time, Then Clean and Fence the Customer's Text
  • Prompt Revision Driven by Evals: Name the Cause, Change One Thing, Rerun the Whole Suite
  • Long-Running Sessions: Compact, Prune, Isolate or Start Fresh, Decided by Naming the Failure
  • Context Isolation Through Subagents: Read the Logs Elsewhere, Keep One Line
  • Defensive Parsing of Claude Replies: Check the Stop Reason, Read the Block or the Text, Then Validate the Values
  • Full Context or Retrieval: Choose by Corpus Size, Cost and Freshness
  • Skepticism Toward Confident Output: Check the Quote, the Record and the Sum Before You Send
  • Debugging a Claude App: Three Error Types, the Recovery Each One Earns, and the First Failing Row
  • Six Ways a 200 Can Still Be Wrong: Hallucination, Refusal, Under-Acting, Context Loss, Format Drift and Inconsistency
  • Fix the Cause, Not the Symptom: Four Recovery Drills for an LLM App, Each Checked on a New Input
  • Integration Layer or Model Output? Three Taps and Three Questions to Find Where a Wrong Answer Lives
  • Which Test Layer Owns the Failure? Unit, Functional, Integration and End-to-End Tests for a Claude App
  • Designing an Overnight Document Pipeline on Claude: Batch Lane, Live Lane, a Cached Prefix and a custom_id Reconcile
  • Proving a Model Upgrade Is Ready: A Frozen Golden Set, a Calibrated Judge, the Right Layer and a Release Gate
  • From Requirement to Design for a Claude App: Eight Requirements, Five Elements and a Trace With No Gaps
  • Build a Claude Refund App: the Messages API, Two Tools, an MCP Server and a Hook in One Loop
  • Ship a Claude App: an Eval Gate, Two Guardrail Layers, a Cost Check From usage and a Pinned Model
  • Lab: a 30-Case Golden Set, a Calibrated Judge and a Per-Slice CI Gate on a Claude Refund App
  • Lab: Cut a Claude App's Bill by 62 Percent With Usage Data, Layered Cache Breakpoints and a Batch Job
  • Lab: Three Planted Bugs in a Claude App, a Vague Prompt, a Mistyped Tool Schema and a Broken Stream Handler
  • Lab: Three Planted Bugs in a Claude Code CI Repo, a Permission Mode, a Plugin Path and an MCP Token Variable
  • Lab: Harden a Claude App, an Uncalibrated Judge, a Retry Loop That Retries Everything and a Hook Matcher With a Gap
  • Lab: Turn a Claude App Into a Reusable Template, One Pinned Model Id, No Key in Code and Evals Built From Data
  • Building an MCP Server: Tools, Resources and Prompts in Python and TypeScript
  • MCP Transports: stdio or Streamable HTTP, and Who Starts the Server
  • Deploying and Authenticating an MCP Server: Environment Keys for stdio, Bearer Tokens and Scopes for HTTP
  1. Blog
  2. /
  3. Claude
  4. /
  5. Building with the Claude API

Getting Data Into Claude: PDF Documents, the Files API, Search Results and Citations

Four documented ways to put your data in front of Claude: a PDF document block, a file uploaded once and sent by file_id, search_result blocks from your own retrieval, and citations on every claim. Then mixed formats in one request, and how to read a 400 or 413 when a file is refused.

Chaand Sheikh

·27 November 2026Building with the Claude API

What you will learn

  • Send a PDF to Claude as a document block, inline as base64 or by file_id
  • Upload a file once with the Files API and pick the right block for each file type
  • Return your own retrieval hits as search_result blocks and read the citations that come back
  • Diagnose a 400 or 413 from an ingestion request by reading the status, then the file's metadata

Before you start

  • The Claude Messages API: your first call
  • Claude tool use: tool_use and tool_result
  • Basic Python

A support agent answers questions from the shop's returns policy. The policy is a PDF. Sometimes it's a handful of snippets from your own search. And a customer who asks "can I return a sale item?" deserves to see where the answer came from.

Three problems show up in a first version: the same PDF is sent again with every request, retrieved snippets are pasted in as plain text, and the answers come back with no source. The result is slow, costly and hard to trust. The Claude docs describe one option for each problem: PDF support, the Files API, search results and citations. This article walks through all four in a small SupportDesk project, then follows a claims agent that sends three file types in one request and learns to read the error when a file is refused.

Answering from a handbook

Picture a colleague who has to answer from a handbook. You can get the book in front of them in four ways:

  • Hand over a photocopy, every time. That's sending the PDF inline.
  • Put the book in a locker once and hand out the locker number. That's the Files API, and the number is the file_id.
  • Ask a librarian, who brings back only the matching pages. Those are search results.
  • Ask the colleague to flag the page they read. That's citations.

Same handbook, four ways in. You choose by where the book lives, and whether the customer must see the page.

Four ways to get data in

OptionWhat you sendUse it when
PDF supportA document block with a base64 or URL sourceOne PDF, one request. Claude reads the text and the page images.
Files APIUpload once (up to 500 MB a file), then a document block with a file source and the file_idThe same file goes into many requests
Search resultssearch_result blocks: a source, a title and the contentYour own retrieval returns snippets
Citations"citations": {"enabled": true} on the blockEach claim must point back to its source

The first two move files. The third moves snippets. The fourth adds the source to the answer.

blocks.py: three content blocks

Everything reaches Claude as a content block in the user message. The project builds the three blocks in one small file:

"""Three ways to hand Claude your data. Each function returns one content block."""
import base64
import pathlib

TITLE = "Returns policy"


def pdf_inline(path):
    raw = pathlib.Path(path).read_bytes()
    data = base64.standard_b64encode(raw).decode()
    return {"type": "document", "title": TITLE,
            "source": {"type": "base64",
                       "media_type": "application/pdf",
                       "data": data},
            "citations": {"enabled": True}}


def pdf_by_id(file_id):
    return {"type": "document", "title": TITLE,
            "source": {"type": "file", "file_id": file_id},
            "citations": {"enabled": True}}


def search_result(source, title, text):
    return {"type": "search_result", "source": source,
            "title": title,
            "content": [{"type": "text", "text": text}],
            "citations": {"enabled": True}}
  • pdf_inline: the source type is base64, so the bytes ride along in the request.
  • pdf_by_id: the source type is file, and only the id travels.
  • search_result: a source, a title, and the content as text blocks.
  • Every block switches citations on.

feed.py: where the data goes in

The data feed uploads once, asks by id, and runs a search tool. Here are the parts that matter (the full file is in the project):

def upload(client, path):
    with open(path, "rb") as f:
        up = client.files.upload(file=(NAME, f, "application/pdf"))
    return up.id


def ask_by_id(client, file_id, question):
    doc = blocks.pdf_by_id(file_id)
    return ask(client, [doc, {"type": "text", "text": question}])


def search_policies(query):
    words = set(query.lower().split())
    hits = [k for k in KB if words & set(k[2].lower().split())]
    return [blocks.search_result(*k) for k in hits]


def ask_with_search(client, question):
    msgs = [{"role": "user", "content": question}]
    r = ask_tools(client, msgs)
    use = next(b for b in r.content if b.type == "tool_use")
    results = search_policies(use.input["query"])
    msgs += [{"role": "assistant", "content": r.content},
             {"role": "user", "content": [{
                 "type": "tool_result",
                 "tool_use_id": use.id,
                 "content": results}]}]
    return ask_tools(client, msgs)


def citations(r):
    """Every citation on every text block."""
    return [(b.text, c) for b in r.content if b.type == "text"
            for c in (b.citations or [])]

Three things to notice:

  • upload runs once and hands back a file id. Later requests build the document from that id and nothing else. The Files API lives at client.files in the current SDK.
  • For search, Claude first asks for your tool. Your own retrieval runs, and the hits go back inside the tool_result as search_result blocks, not as pasted text. (The tool round trip itself is covered in Claude tool use: tool_use and tool_result.)
  • When the answer arrives, the citations are read off each text block.

What each request carried

The project runs against a stand-in: the real Anthropic SDK talks to an httpx mock transport that answers like the Messages and Files APIs. The replies are scripted, but the request sizes are measured from the real request bodies of a small two-page demo PDF.

inline PDF     request  1728 bytes | page_location p.1
upload         request  1261 bytes | file_test_0001
file_id        request   264 bytes | page_location p.2
search result  request   903 bytes | search_result_location kb://sale-items
               2 results sent, 1 cited: Sale items
citations + structured output -> 400 invalid_request_error
The file travels once, later requests carry the id Request size, demo PDF (bytes) inline PDF 1728 upload (once) 1261 by file_id 264 search results 903 Every later request by id stays small. The saving grows with the file.
Measured on the lecture's small demo PDF. Upload once, then send only the id.

Reading the run line by line:

  • The inline PDF answer cites page 1, with a page_location citation.
  • The upload prints a file id, once.
  • By file id, the request shrinks from 1728 to 264 bytes, and the answer cites page 2.
  • Two search results were sent, and the answer cited one of them by its source, kb://sale-items.
  • The last line: citations plus a structured output format is a 400. You have to choose one of the two.

A citation points back

A cited answer comes back as text blocks, and each block carries a list of citations. A PDF citation holds the cited text, the document title, and a start and end page. The end page is exclusive, so start_page_number: 2, end_page_number: 3 means page 2. The cited text doesn't count toward output tokens.

The citation type follows the source you sent:

SourceCitation type
Plain text documentchar_location
PDF documentpage_location
Custom content documentcontent_block_location
search_result blocksearch_result_location

That's how the run could print p.2 for the PDF and kb://sale-items for the search hit: the answer carries where each claim came from. For the wider question of what a citation proves in a retrieval app, see Citations and abstention in RAG.

Mixed formats: the file type picks the block

Now a second use case from the follow-up lecture. A claims agent reviews damage claims. Each claim comes with a policy PDF, a photo of the box and a notes file, and they must travel together in one request.

Think of a parcel depot. You leave a parcel once and get a ticket (the file id). Later you show the ticket, not the parcel. Each kind of parcel has its own counter, and a parcel can be refused at the desk: wrong counter, or too heavy.

FileMIME typeInput blockWatch for
PDFapplication/pdfdocumentNo password; up to 600 pages on current models
Plain texttext/plaindocumentUpload it as text/plain
Imagejpeg, png, gif, webpimageAll four take the same block
Word, Excel.docx, .xlsxnoneConvert to text or PDF first
Other data filesother typesnoneGoes to the code execution tool as a container upload

The project's blocks.py turns that table into one function, and refuses an unknown type before any request is sent:

"""Pick the input block for a file, by its type. Each function returns a block."""
import base64
import pathlib

IMAGES = ("image/jpeg", "image/png", "image/gif", "image/webp")
DOCS = ("application/pdf", "text/plain")


def block_type(mime):
    if mime in IMAGES:
        return "image"
    if mime in DOCS:
        return "document"
    raise ValueError(f"{mime}: convert to text or PDF first")


def by_id(file_id, mime):
    return {"type": block_type(mime),
            "source": {"type": "file", "file_id": file_id}}


def inline(path, mime):
    raw = pathlib.Path(path).read_bytes()
    data = base64.standard_b64encode(raw).decode()
    source = {"type": "base64", "media_type": mime, "data": data}
    return {"type": block_type(mime), "source": source}


def as_text(label, text):
    return {"type": "text", "text": f"{label}:\n{text}"}

Image blocks and the base64 options are covered in more depth in images, PDFs and thinking blocks. Here the point is the rule: the block type has to match the file's MIME type, whether you send bytes or an id.

The file type picks the block jpeg, png, gif, webp pdf, text/plain .docx and others block_type() image block document block refused: convert first
One check before the request: the block must fit the file type.

ingest.py: upload once, diagnose a refusal

The intake uploads each file once, puts many files in one request by id, and names the fault when a request fails:

def ask_mixed(client, files, question):
    content = [blocks.by_id(fid, mime) for fid, mime in files]
    content.append({"type": "text", "text": question})
    return ask(client, content)


def diagnose(client, content, err):
    """Name the fault from the status code and the file's own metadata."""
    if err.status_code == 413:
        return "size limit: send the big file by file id"
    for b in content:
        src = b.get("source", {})
        if src.get("type") != "file":
            continue
        mime = client.files.retrieve_metadata(src["file_id"]).mime_type
        try:
            want = blocks.block_type(mime)
        except ValueError:
            return "unsupported format: convert to text or PDF first"
        if want != b["type"]:
            return f"wrong block type: {want} block needed for {mime}"
    return "no file fault found"

The method is the same every time: read the status first. A 413 means size. Otherwise read the file's own metadata to learn its real type, and compare it with the block you sent.

The run uploads three files, sends one mixed request, then builds three faulty requests on purpose (again against the stand-in, whose size cap is set to 50,000 bytes so a 413 fits on a laptop):

upload returns_policy.pdf  application/pdf  file_test_0001
upload damaged_box.png     image/png        file_test_0002
upload agent_notes.txt     text/plain       file_test_0003
by file id  request   360 bytes | document image document text
inline      request  2385 bytes | document image document text
fault 1: 400 invalid_request_error
         wrong block type: image block needed for image/png
fault 2: 400 invalid_request_error
         unsupported format: convert to text or PDF first
fault 3: 413 request_too_large
         size limit: send the big file by file id
fixed: docx as a text block -> end_turn
fixed: big scan by file id  -> end_turn

Three file types travel in one request: a document, an image, another document and the text question. By id, that request is 360 bytes; inline, the same files make it 2385. Then the three faults:

SymptomCauseFix
400, wrong block typeAn image file sent in a document blockMatch the block to the file type
400, unsupported formatA Word file sent in a document blockConvert to text or PDF, or send the text as a text block
413, request too largeA big scan sent inline as base64Upload once and send the file id

Retrying the same request won't help with any of these. Each one is fixed by changing the request.

Common mistakes

  • Trusting a file id typed by a user. Files are shared across the workspace, so any key there can read any file. Keep the map from user to file on your own server.
  • Citations together with a structured output format. The API answers with a 400, as the run showed. Pick one.
  • Expecting citations from a scanned PDF. With no extractable text, there's nothing to cite.
  • Mixed citation settings across search results. All search_result blocks in one request must use the same setting.
  • Pasting retrieved snippets as plain text. Send them as search_result blocks, so the answer can cite them.
  • Resending the whole PDF on every turn. Upload it once and send the id.

Quick recap

The caseThe input
A photo of a cracked boximage block
The signed policy, a PDFdocument block
Agent notes in a text filedocument block, text/plain
The same PDF in every requestUpload once, send the file_id
A customer letter in WordConvert it, then a text block
Snippets from your own searchsearch_result blocks in the tool_result
The customer must see the sourcecitations: {enabled: true}

Choose the way in by where the data lives, and keep the source on every claim.

Try it yourself

Add a fourth policy article to KB in feed.py, for example one about gift cards, and ask "Can I return a gift card?". Which search_result blocks does search_policies send, and which source should the citation point to?

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in Claude · 17 of 66

Previous
Images, PDFs and Thinking Blocks in the Claude Messages API: Typed Blocks In, Typed Blocks Out
Next post
Opus, Sonnet or Haiku: Pick the Claude Model per Job, and Test the Request When a New Release Arrives

Related course on Udemy

Claude Certified Developer - Foundations (CCDV-F) Exam Prep

Build and ship Claude apps: the API, agents, tools and MCP, prompts, evals, security and model choice.View on Udemy ↗: Claude Certified Developer - Foundations (CCDV-F) Exam Prep (paid course, opens in a new tab)

Related posts

The Claude Messages API: Your First Call, Field by Field

One request in, one Message out. The four fields of a Messages API call (model, max_tokens, system, messages), how to read content blocks, stop_reason and usage, and why every turn resends the history.

Claude Tool Use: How tool_use and tool_result Work in the Messages API

Follow one order question through Claude's tool round trip: define a tool, read the tool_use block, run your own function and send a matching tool_result back, including parallel calls and is_error.

Claude Client SDKs Wrap One REST API: Raw HTTP, Python, TypeScript and Async Calls Compared

Every Claude client SDK wraps the same REST request: a POST to /v1/messages with a JSON body. See it built by hand, through the Python and TypeScript SDKs, as typed errors, and as async calls that wait together.

Anthropic SDK Timeouts, Retries and Error Classes: Configure the Client Once, Then Give 429, 529, 400 and Timeouts Their Own Move

Configure the Anthropic SDK client (timeout, max_retries, with_options, async, pagination), see which errors it retries by itself, then repair a retry wrapper so a 429, a 529, a 400 and a timeout each get the move the docs support.

On this page

  • Answering from a handbook
  • Four ways to get data in
  • blocks.py: three content blocks
  • feed.py: where the data goes in
  • What each request carried
  • A citation points back
  • Mixed formats: the file type picks the block
  • ingest.py: upload once, diagnose a refusal
  • Common mistakes
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

Claude Certified Developer - Foundations (CCDV-F) Exam Prep

Build and ship Claude apps: the API, agents, tools and MCP, prompts, evals, security and model choice.View on Udemy ↗: Claude Certified Developer - Foundations (CCDV-F) Exam Prep (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact usFAQs
Legal
Terms of ServicePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.