How to Perform File Uploads Using the Anthropic Python SDK
Upload files to Anthropic's API by accessing client.beta.files.upload() with a file path, bytes, or file-like object, which returns a FileMetadata object containing the assigned file ID.
The anthropics/anthropic-sdk-python repository provides a type-safe, ergonomic interface for interacting with Anthropic's API. Understanding how to perform file uploads using the Anthropic Python SDK requires familiarity with its layered architecture, which cleanly separates the HTTP client, beta resource groups, and specific endpoint implementations.
Understanding the SDK Architecture for File Uploads
The SDK organizes file operations through a hierarchical structure that routes requests from the main client down to specialized resource classes.
The Client Layer
The Anthropic class serves as the primary entry point, handling authentication via the ANTHROPIC_API_KEY environment variable or explicit api_key parameter, configuring base URLs, and managing retry logic. This class exposes the beta property, which lazy-loads beta-specific resources.
Source: src/anthropic/_client.py
The Beta Resource Group
The beta namespace isolates experimental APIs under client.beta. This group dynamically loads sub-resources like files only when accessed, preventing unnecessary initialization overhead.
Source: src/anthropic/resources/beta/__init__.py
The Files Resource
The Files class implements the file-related endpoints including list, delete, download, retrieve_metadata, and upload. The synchronous implementation resides in src/anthropic/resources/beta/files.py (lines 75-89), while the asynchronous counterpart occupies lines 69-80 in the same file.
The upload method constructs a multipart/form-data request, extracts the file payload using extract_files, adds the required Content-Type header, and invokes the generic _post helper inherited from SyncAPIResource or AsyncAPIResource.
How to Upload Files Using the Anthropic Python SDK
The SDK accepts multiple input types through the FileTypes union defined in src/anthropic/_types.py: str (file path), bytes, or io.IOBase (file-like objects).
Synchronous File Upload
The most common approach opens a local file path and returns a FileMetadata object containing the file ID, size, and MIME type.
from anthropic import Anthropic
client = Anthropic() # Reads ANTHROPIC_API_KEY from environment
# Upload a local file; SDK returns metadata with generated file_id
metadata = client.beta.files.upload(file="my_image.png")
print(f"Uploaded file ID: {metadata.id}")
print(f"Size (bytes): {metadata.bytes}")
print(f"MIME type: {metadata.mime_type}")
Uploading Raw Bytes
For in-memory data, pass a bytes object directly without writing to disk.
from anthropic import Anthropic
client = Anthropic()
image_bytes = b"\x89PNG..." # Binary content of a PNG image
metadata = client.beta.files.upload(file=image_bytes)
print(metadata.id)
Asynchronous File Upload
For non-blocking I/O, use AsyncAnthropic with async/await syntax.
import asyncio
from anthropic import AsyncAnthropic
async def main() -> None:
client = AsyncAnthropic()
async with client:
metadata = await client.beta.files.upload(file="document.pdf")
print(f"File ID: {metadata.id}")
asyncio.run(main())
Using File-Like Objects
Any object implementing the io.IOBase protocol works, including opened file handles.
from anthropic import Anthropic
client = Anthropic()
with open("report.txt", "rb") as f:
metadata = client.beta.files.upload(file=f)
print(metadata.id)
Understanding the Upload Implementation
Under the hood, the upload method in src/anthropic/resources/beta/files.py performs several critical operations:
- Header Construction: Injects the required
anthropic-beta: files-api-2025-04-14header to access the beta files API - Body Preparation: Creates a deep copy of the request body containing the file reference
- File Extraction: Uses
extract_filesto parse theFileTypesinput and prepare multipart boundaries - Content-Type Override: Sets
Content-Type: multipart/form-datato ensure proper MIME handling - HTTP POST: Dispatches to
/v1/files?beta=truevia the inherited_postmethod and casts the response toFileMetadata
This architecture ensures type safety while supporting multiple input formats through the FileTypes union.
Summary
- Access file uploads through
client.beta.files.upload()using theAnthropicorAsyncAnthropicclient - The SDK accepts
strpaths,bytesobjects, orio.IOBasefile-like objects via theFileTypesunion - Uploads return a
FileMetadataobject containing the file ID, size, and MIME type - The implementation resides in
src/anthropic/resources/beta/files.pyand requires thefiles-api-2025-04-14beta header - Both synchronous and asynchronous patterns are fully supported through the unified resource interface
Frequently Asked Questions
What file types does the Anthropic Python SDK support for uploads?
The SDK accepts any file type through the FileTypes union defined in src/anthropic/_types.py, which includes str (file system paths), bytes (in-memory binary data), and io.IOBase (file-like objects such as opened file handles or BytesIO streams). The API itself may impose restrictions on specific MIME types or file sizes depending on the endpoint configuration.
How do I handle asynchronous file uploads in the Anthropic SDK?
Use the AsyncAnthropic client class instead of the standard Anthropic client. The asynchronous files resource is available at client.beta.files and supports await syntax for non-blocking uploads. The implementation in src/anthropic/resources/beta/files.py (lines 69-80) handles the async HTTP POST operation while maintaining the same FileTypes input flexibility as the synchronous version.
Where is the file upload implementation located in the source code?
The core upload logic resides in src/anthropic/resources/beta/files.py within the Files class. The synchronous upload method spans lines 75-89, while the asynchronous variant occupies lines 69-80. This method constructs the multipart request body, extracts file data using extract_files, sets the required anthropic-beta: files-api-2025-04-14 header, and dispatches the POST request to /v1/files?beta=true via the inherited _post helper from the base resource classes.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →