Files Resource Reference
Purpose and Scope
This page is a reference for the file-related surface in the Anthropic TypeScript SDK. It focuses on the beta files resource, the upload helper behavior that prepares local data for multipart requests, and the form encoding rules that affect file upload calls. Use it when you need to upload a file, list or manage uploaded files, download file contents, inspect metadata, or understand why a particular value is accepted or rejected before a request is sent. The official API treats files as beta resources, so request parameters can include beta headers while the SDK presents the operations through the beta namespace.
The repository evidence for this page comes from the generated resource tests and the upload/form tests. The resource tests show the public call patterns exercised against the beta files client, including response wrappers and request options. The upload tests show what the public toFile helper accepts and how it derives file names, MIME types, and other properties. The form tests show how multipart payloads are assembled and validated, including edge cases for null and undefined values. Together these tests describe both the API methods users call and the local data conversion behavior that happens before the HTTP request is built.
Sources: tests/api-resources/beta/files.test.ts, tests/uploads.test.ts, tests/form.test.ts, api.md
Relevant Source Files
- tests/api-resources/beta/files.test.ts — Exercises the public beta files resource methods from an Anthropic client, including list, delete, download, retrieveMetadata, and upload, plus request options and response wrapper behavior.
- tests/uploads.test.ts — Exercises the exported toFile helper used to convert Files, Blobs, Buffers, streams, and response-like objects into uploadable File instances, including naming and override behavior.
- tests/form.test.ts — Exercises multipart form construction and validation, including accepted primitive and binary values, rejected null values, and stripping of undefined values from nested objects and arrays.
- api.md — Provides generated API reference context for the SDK surface and should be used as the broad reference anchor for method names and resource organization.
Public Resource Surface
The files resource is accessed from the beta namespace on an Anthropic client. The generated tests instantiate a client with an API key and base URL, then call client.beta.files methods. The exercised methods are list, delete, download, retrieveMetadata, and upload. Each method returns the SDK promise wrapper used across generated resources: it can be awaited for parsed data, converted to the raw Response with asResponse, or awaited with withResponse to obtain both the parsed data and the raw response. This is important for file workflows because callers often need either high-level metadata or lower-level headers and status information.
The list operation accepts pagination and filtering parameters. The test passes after_id, before_id, limit, and scope_id, along with a betas array, which demonstrates that the SDK forwards both query parameters and beta header selection through the normal params object. The official API documentation describes files as beta and documents pagination defaults and limits for listing. In practice, treat list as the discovery operation for uploaded files and use scope_id when you only want files associated with a particular context, such as a session-managed workflow. The tests validate request option propagation by overriding the path and expecting the SDK error type for a not-found route.
Deletion, download, and metadata retrieval are all keyed by a file identifier. The tests call delete with a file_id, download with a file_id, and retrieveMetadata with a file_id. They also pass betas for these operations in the params position and request options separately, which establishes the calling shape: the identifier is positional, beta parameters are supplied as a small object, and per-request options remain a final argument. Retrieve metadata returns parsed data through the same response wrapper pattern, while download is tested primarily for request construction and error propagation because binary response handling depends on the service response.
Sources: tests/api-resources/beta/files.test.ts, api.md
Upload Inputs and toFile Behavior
The upload operation takes a body containing a file value. The generated resource test creates the upload body by calling toFile on a Buffer and supplying README.md as the filename, then passes the result as file. That call pattern is the safest way to upload in Node-style code because it turns raw bytes into a File-like object with an explicit name. The official API describes upload as a POST to the files endpoint returning file metadata such as id, filename, MIME type, byte size, type, downloadable, and optional scope. The SDK test confirms that upload participates in the same response wrapper contract as other resources.
The toFile helper is intentionally stricter than simply accepting any JavaScript value. The upload tests verify that unexpected objects produce helpful errors that name the data type, constructor, and visible properties. That behavior is useful when a caller accidentally passes an application object instead of a Blob, File, Buffer, stream, or response-like object. The tests also intentionally show that plain strings are not supported at the type level because accepting strings could lead users to pass a file path when the API needs file contents. Although the runtime can create a file from a string in the test, the type-level restriction is the documented safety signal.
File naming is derived from the input when possible. A response-like object with a URL ending in an audio filename becomes a File named after the URL segment. A File input keeps its existing name. A Node read stream created from a test path becomes a File named after the basename of that path, and its type is empty unless the caller overrides it. These rules matter because the service returns original filenames in file metadata, and because downstream workflows may show or mount files by name. When stable names matter, pass an explicit filename instead of relying on inference.
Property override behavior is also explicit. For a read stream, the caller can preserve the inferred filename while setting properties such as MIME type, or can provide a new filename and metadata such as lastModified. For an existing File, toFile does not copy the object by default, which keeps the operation cheap and preserves name and type. If a new filename, type, or lastModified value is supplied, the helper creates a different File with the requested properties. The tests also prove that the result is assignable to both File and Blob, which is the shape expected by multipart form construction.
Sources: tests/uploads.test.ts, tests/api-resources/beta/files.test.ts
Multipart Form Construction
File upload requests are sent as multipart form data, and the form tests define several practical rules for request bodies. Valid multipart values include strings, numbers, booleans, a File returned by toFile from a Buffer, and a Blob with a content type. This means callers can combine the required file field with other scalar form fields when an endpoint supports them. The tests call multipartFormRequestOptions and createForm with the runtime fetch object, which indicates that form construction is designed to adapt to the fetch implementation available in the supported server-side JavaScript runtime.
Null and undefined are handled differently. A null value in a form body is rejected with a TypeError, which prevents ambiguous multipart fields from being sent. Undefined values are stripped instead of serialized. At the top level, an undefined field is omitted while a defined sibling remains. In nested objects, an undefined property is omitted; if no defined nested properties remain, the nested object contributes no entries. In arrays, undefined items are stripped, and defined items are emitted using bracket-style array notation. These rules reduce accidental wire-level noise while still failing clearly on null, which is usually an intentional but unsupported value.
The nested encoding behavior is relevant even when the primary file upload call only needs one file field, because the same internal form builder is used by multipart endpoints throughout the SDK. The tests show object keys encoded with bracket notation, such as a nested string under a parent object, and array values encoded with an empty bracket suffix. If you are debugging a request that seems to lose optional fields, check whether those fields are undefined. If you are debugging a TypeError before the network request, check whether a field was explicitly set to null.
Sources: tests/form.test.ts, tests/uploads.test.ts
Compact Method Reference
| Operation | SDK call shape shown by tests | Main parameters | Notes |
|---|---|---|---|
| List files | client.beta.files.list(params?, options?) | after_id, before_id, limit, scope_id, betas | Returns a paginated parsed response; supports raw and combined response wrappers. |
| Upload file | client.beta.files.upload({ file }) | file produced by toFile or another uploadable File-like value | Sends multipart form data and returns file metadata. |
| Retrieve metadata | client.beta.files.retrieveMetadata(file_id, params?, options?) | file_id, betas | Fetches metadata for a single uploaded file. |
| Download | client.beta.files.download(file_id, params?, options?) | file_id, betas | Builds a download request for the identified file. |
| Delete | client.beta.files.delete(file_id, params?, options?) | file_id, betas | Deletes or removes the identified file resource according to API behavior. |
Use the params object for API-level inputs such as pagination, filtering, and beta selection. Use the final request options argument for SDK transport overrides such as a custom path in tests, headers, timeout, or other per-request options supported by the client. The resource tests deliberately pass an invalid path through request options and assert a NotFoundError, which demonstrates that request options are forwarded to the request layer rather than ignored. The same tests also demonstrate that asResponse and withResponse are available, so callers can choose between ergonomic parsed data and lower-level inspection without changing the resource method they call.
Session Resource Relationship
Files become especially useful in Managed Agent session flows. The official session resources API describes adding a previously uploaded file to a session by sending a file_id, a type of file, and an optional mount path. Although this page is centered on the files resource itself, that relationship explains why file metadata can include scope and why list supports scope filtering. A typical workflow uploads data once, receives the file identifier, then attaches that identifier to a session resource so an agent can read it from the session environment. If the mount path is omitted, the API provides a default upload mount location.
From an SDK perspective, keep the lifecycle separate. Upload creates the file resource and returns metadata. Session resource APIs consume the file identifier when mounting it into an agent session. Listing can then be used for broad discovery or scoped inspection, while retrieveMetadata gives information for one identifier and download retrieves file contents when available. This separation is useful for retries and error handling: if upload succeeds but session creation fails, the file identifier can still be reused; if mounting fails, inspect the file metadata before attempting another session operation.
Sources: tests/api-resources/beta/files.test.ts, api.md
Usage Guidance and Edge Cases
Prefer toFile when you are not already holding a standards-compatible File. In Node, pass a Buffer with an explicit filename for generated content, or pass a read stream when reading from disk. If you use a read stream and need the service-visible MIME type, provide the type override because the tested default type for a stream is empty. If you already have a File and do not need to rename or retag it, passing it through toFile is cheap because the helper returns the original object. If you do need to rename it, supply the new filename and metadata overrides intentionally.
When troubleshooting upload failures, first distinguish client-side construction errors from API errors. A helpful unexpected data type error means toFile received an unsupported object before the request was sent. A TypeError from multipart form validation can mean a body field was null. A not-found SDK error in the generated resource tests is caused by an intentionally invalid request path, which shows how API errors surface through typed SDK errors. For successful calls, use asResponse when status codes, headers, or raw response handling matter, and use withResponse when you need both parsed metadata and transport details.
Next Steps
For basic file uploads, start with the upload operation and toFile helper behavior described here. For agent workflows, continue to the Managed Agent files and session resources documentation, because uploaded file identifiers are mounted into sessions through a different beta resource. For lower-level request troubleshooting, read the request options, errors, and retries page so you can apply per-request options consistently across file list, metadata, download, delete, and upload operations. For runtime-specific behavior, review runtime support before relying on File, Blob, fetch, or stream behavior in a new deployment environment.