SPB Git

Repository Public

files.md 36.7 KB 1,059 lines markdown

1---2title: Files API3url: https://platform.claude.com/docs/en/build-with-claude/files4description: Upload files once, reference them by file_id in Messages requests, and download outputs created by skills or the code execution tool.5---67## Compatibility8- [ZDR](https://platform.claude.com/docs/en/manage-claude/api-and-data-retention): not eligible9- Platforms: Claude API, Claude Platform on AWS (beta), Microsoft Foundry (beta) [1]; not available on Amazon Bedrock, Google Cloud101. On [Microsoft Foundry](https://platform.claude.com/docs/en/build-with-claude/claude-in-microsoft-foundry), the Files API requires a [Hosted on Anthropic deployment](https://platform.claude.com/docs/en/build-with-claude/claude-in-microsoft-foundry#additional-features-not-supported-when-hosted-on-azure).1112The Files API lets you upload and manage files to use with the Claude API without re-uploading content with each request. This is particularly useful when using the [code execution tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/code-execution-tool) to provide inputs (for example, datasets and documents) and then download outputs (for example, charts). You can [explore the API reference directly](https://platform.claude.com/docs/en/api/files/upload), in addition to this guide.1314## File type support1516Referencing a `file_id` in a Messages request is supported on all models that support the given file type. [Images](https://platform.claude.com/docs/en/build-with-claude/vision) are supported on all current Claude models. For [PDFs](https://platform.claude.com/docs/en/build-with-claude/pdf-support) and [other file types with the code execution tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/code-execution-tool#compatibility), see the linked pages for model support.1718## How the Files API works1920The Files API provides a create-once, use-many-times approach for working with files:2122* **Upload files** to Anthropic's secure storage and receive a unique `file_id`23* **Download files** that are created by skills or the code execution tool24* **Reference files** in [Messages](https://platform.claude.com/docs/en/api/messages/create) requests using the `file_id` instead of re-uploading content25* **Manage your files** with list, retrieve, and delete operations2627<Warning id="workspace-scoped-access">28  **Uploaded files are accessible to your entire workspace, not scoped to an end user, conversation, or session.** Any API key with access to a workspace can access any files uploaded to that workspace. Every service account, and every user whose organization role allows API access, can use the Default Workspace in addition to any workspace you add them to, so keep files that must stay separate in their own [workspace](https://platform.claude.com/docs/en/manage-claude/workspaces#api-keys-and-resource-scoping) and access them only with keys scoped to that workspace. Never accept `file_id` values from end users or other untrusted sources: a user-supplied file ID would let one user of your application read content that another user uploaded. Treat file IDs as server-side references, and keep the mapping between your users and their files in your application.2930  If you are building a multi-tenant application on the Files API, create a separate [workspace](https://platform.claude.com/docs/en/manage-claude/workspaces) for each tenant. The workspace is the isolation boundary for files, so a workspace per tenant gives each tenant's data hard isolation from every other tenant. Each organization can have up to 100 workspaces; contact your account team if you need more.31</Warning>3233## How to use the Files API3435### Uploading a file3637Upload a file to be referenced in future API calls:3839<CodeGroup>40  ```bash cURL41  FILE_ID=$(curl -X POST https://api.anthropic.com/v1/files \42    -H "x-api-key: $ANTHROPIC_API_KEY" \43    -H "anthropic-version: 2023-06-01" \44    -F "file=@/path/to/document.pdf" | jq -r '.id')45  echo "$FILE_ID"46  ```4748  ```bash CLI49  FILE_ID=$(ant files upload \50    --file /path/to/document.pdf \51    --transform id \52    --raw-output)53  echo "$FILE_ID"54  ```5556  ```python Python57  uploaded = client.files.upload(58      file=("document.pdf", open("/path/to/document.pdf", "rb"), "application/pdf"),59  )60  file_id = uploaded.id61  print(file_id)62  ```6364  ```typescript TypeScript65  const uploaded = await client.files.upload({66    file: await toFile(67      fs.createReadStream("/path/to/document.pdf"),68      undefined,69      { type: "application/pdf" },70    ),71  });72  console.log(uploaded.id);73  ```7475  ```csharp C#76  var uploaded = await client.Files.Upload(77      new FileUploadParams78      {79          File = new BinaryContent80          {81              Stream = File.OpenRead("/path/to/document.pdf"),82              FileName = "document.pdf",83              ContentType = new("application/pdf")84          }85      });8687  var fileId = uploaded.ID;88  Console.WriteLine(fileId);89  ```9091  ```go Go92  f, err := os.Open("/path/to/document.pdf")93  if err != nil {94  	log.Fatal(err)95  }96  defer f.Close()9798  response, err := client.Files.Upload(context.Background(),99  	anthropic.FileUploadParams{100  		File: anthropic.File(f, "document.pdf", "application/pdf"),101  	})102  if err != nil {103  	log.Fatal(err)104  }105106  fileID := response.ID107  fmt.Println(fileID)108  ```109110  ```java Java111  FileMetadata file = client.files().upload(112      FileUploadParams.builder()113          .file(MultipartField.<InputStream>builder()114              .value(Files.newInputStream(Path.of("/path/to/document.pdf")))115              .filename("document.pdf")116              .contentType("application/pdf")117              .build())118          .build()119  );120121  String fileId = file.id();122  System.out.println(fileId);123  ```124125  ```php PHP126  $file = $client->files->upload(127      file: FileParam::fromResource(fopen('/path/to/document.pdf', 'rb'), contentType: 'application/pdf'),128  );129130  $fileId = $file->id;131  echo $fileId;132  ```133134  ```ruby Ruby135  file = client.files.upload(136    file: Anthropic::FilePart.new(137      Pathname("/path/to/document.pdf"),138      content_type: "application/pdf"139    )140  )141142  file_id = file.id143  puts file_id144  ```145</CodeGroup>146147The response from uploading a file includes:148149```json Response150{151  "id": "file_011CNha8iCJcU1wXNR6q4V8w",152  "type": "file",153  "filename": "document.pdf",154  "mime_type": "application/pdf",155  "size_bytes": 1024000,156  "created_at": "2025-01-01T00:00:00Z",157  "downloadable": false,158  "expires_at": null159}160```161162`downloadable` is `false` for files you upload. Only files created by [skills](https://platform.claude.com/docs/en/build-with-claude/skills-guide) or the [code execution tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/code-execution-tool) can be downloaded. See [Downloading a file](https://platform.claude.com/docs/en/build-with-claude/files#downloading-a-file).163164### Using a file in messages165166Once uploaded, reference the file by passing the `id` from the upload response as `file_id`:167168<CodeGroup>169  ```bash cURL170  curl -X POST https://api.anthropic.com/v1/messages \171    -H "x-api-key: $ANTHROPIC_API_KEY" \172    -H "anthropic-version: 2023-06-01" \173    -H "content-type: application/json" \174    -d @- <<EOF175  {176    "model": "claude-opus-5",177    "max_tokens": 1024,178    "messages": [179      {180        "role": "user",181        "content": [182          {183            "type": "text",184            "text": "Please summarize this document for me."185          },186          {187            "type": "document",188            "source": {189              "type": "file",190              "file_id": "$FILE_ID"191            }192          }193        ]194      }195    ]196  }197  EOF198  ```199200  ```bash CLI201  ant messages create <<YAML202  model: claude-opus-5203  max_tokens: 1024204  messages:205    - role: user206      content:207        - type: text208          text: Please summarize this document for me.209        - type: document210          source:211            type: file212            file_id: $FILE_ID213  YAML214  ```215216  ```python Python217  response = client.messages.create(218      model="claude-opus-5",219      max_tokens=1024,220      messages=[221          {222              "role": "user",223              "content": [224                  {"type": "text", "text": "Please summarize this document for me."},225                  {226                      "type": "document",227                      "source": {228                          "type": "file",229                          "file_id": file_id,230                      },231                  },232              ],233          }234      ],235  )236  print(response)237  ```238239  ```typescript TypeScript240  const response = await client.messages.create({241    model: "claude-opus-5",242    max_tokens: 1024,243    messages: [244      {245        role: "user",246        content: [247          {248            type: "text",249            text: "Please summarize this document for me.",250          },251          {252            type: "document",253            source: {254              type: "file",255              file_id: uploaded.id,256            },257          },258        ],259      },260    ],261  });262263  console.log(response);264  ```265266  ```csharp C#267  var response = await client.Messages.Create(268      new MessageCreateParams269      {270          Model = Model.ClaudeOpus5,271          MaxTokens = 1024,272          Messages =273          [274              new MessageParam275              {276                  Role = Role.User,277                  Content = new List<ContentBlockParam>278                  {279                      new TextBlockParam { Text = "Please summarize this document for me." },280                      new DocumentBlockParam281                      {282                          Source = new FileDocumentSource { FileID = fileId }283                      }284                  }285              }286          ]287      });288289  Console.WriteLine(response);290  ```291292  ```go Go293  msg, err := client.Messages.New(context.Background(),294  	anthropic.MessageNewParams{295  		Model:     anthropic.ModelClaudeOpus5,296  		MaxTokens: 1024,297  		Messages: []anthropic.MessageParam{298  			anthropic.NewUserMessage(299  				anthropic.NewTextBlock("Please summarize this document for me."),300  				anthropic.NewDocumentBlock(anthropic.FileDocumentSourceParam{301  					FileID: fileID,302  				}),303  			),304  		},305  	})306  if err != nil {307  	log.Fatal(err)308  }309310  fmt.Println(msg)311  ```312313  ```java Java314  MessageCreateParams params = MessageCreateParams.builder()315      .model(Model.CLAUDE_OPUS_5)316      .maxTokens(1024)317      .addUserMessageOfBlockParams(List.of(318          ContentBlockParam.ofText(TextBlockParam.builder()319              .text("Please summarize this document for me.")320              .build()),321          ContentBlockParam.ofDocument(DocumentBlockParam.builder()322              .fileSource(fileId)323              .build())324      ))325      .build();326327  Message message = client.messages().create(params);328  System.out.println(message);329  ```330331  ```php PHP332  $response = $client->messages->create(333      maxTokens: 1024,334      messages: [335          [336              'role' => 'user',337              'content' => [338                  ['type' => 'text', 'text' => 'Please summarize this document for me.'],339                  [340                      'type' => 'document',341                      'source' => [342                          'type' => 'file',343                          'fileID' => $fileId,344                      ],345                  ],346              ],347          ],348      ],349      model: 'claude-opus-5',350  );351352  echo $response;353  ```354355  ```ruby Ruby356  response = client.messages.create(357    model: "claude-opus-5",358    max_tokens: 1024,359    messages: [360      {361        role: "user",362        content: [363          { type: "text", text: "Please summarize this document for me." },364          {365            type: "document",366            source: {367              type: "file",368              file_id: file_id369            }370          }371        ]372      }373    ]374  )375376  puts response377  ```378</CodeGroup>379380### File types and content blocks381382The Files API supports different file types that correspond to different content block types:383384| File type                                                                                                                               | MIME type                                            | Content block type | Use case                            |385| --------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------- | ------------------ | ----------------------------------- |386| PDF                                                                                                                                     | `application/pdf`                                    | `document`         | Text analysis, document processing  |387| Plain text                                                                                                                              | `text/plain`                                         | `document`         | Text analysis, processing           |388| Images                                                                                                                                  | `image/jpeg`, `image/png`, `image/gif`, `image/webp` | `image`            | Image analysis, visual tasks        |389| [Datasets, others](https://platform.claude.com/docs/en/agents-and-tools/tool-use/code-execution-tool#upload-and-analyze-your-own-files) | Varies                                               | `container_upload` | Analyze data, create visualizations |390391#### Document blocks392393For PDFs and text files, use the `document` content block:394395```json396{397  "type": "document",398  "source": {399    "type": "file",400    "file_id": "file_011CNha8iCJcU1wXNR6q4V8w"401  },402  "title": "Document Title", // Optional403  "context": "Context about the document", // Optional404  "citations": { "enabled": true } // Optional, enables citations405}406```407408#### Image blocks409410For images, use the `image` content block:411412```json413{414  "type": "image",415  "source": {416    "type": "file",417    "file_id": "file_011CPMxVD3fHLUhvTqtsQA5w"418  }419}420```421422#### Container upload blocks423424To send a file to the [code execution tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/code-execution-tool#upload-and-analyze-your-own-files), use the `container_upload` content block:425426```json427{428  "type": "container_upload",429  "file_id": "file_011CNha8iCJcU1wXNR6q4V8w"430}431```432433### Working with other file formats434435For file types that the `document` block doesn't support (for example, .docx and .xlsx), convert the files to plain text and include the content directly in your message. Files that are already plain text, such as .csv and .md files, can either be read in this way or uploaded through the Files API with an explicit `text/plain` content type. To analyze datasets instead of reading them as text, upload them for the [code execution tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/code-execution-tool#upload-and-analyze-your-own-files) using a `container_upload` block.436437The following examples read a text file and send its contents as plain text:438439<CodeGroup>440  ```bash cURL441  # Read the text file442  # Note: For files with special characters, consider base64 encoding443  TEXT_CONTENT=$(cat document.txt)444445  curl https://api.anthropic.com/v1/messages \446    -H "content-type: application/json" \447    -H "x-api-key: $ANTHROPIC_API_KEY" \448    -H "anthropic-version: 2023-06-01" \449    -d @- <<EOF450  {451    "model": "claude-opus-5",452    "max_tokens": 1024,453    "messages": [454      {455        "role": "user",456        "content": [457          {458            "type": "text",459            "text": "Here's the document content:\n\n${TEXT_CONTENT}\n\nPlease summarize this document."460          }461        ]462      }463    ]464  }465  EOF466  ```467468  ```bash CLI469  # The "@./path" reference inlines the file contents directly into the field.470  ant messages create \471    --model claude-opus-5 \472    --max-tokens 1024 \473    --transform 'content.#(type=="text").text' \474    --raw-output <<'YAML'475  messages:476    - role: user477      content:478        - type: text479          text: "Here's the document content:"480        - type: text481          text: "@./document.txt"482        - type: text483          text: "Please summarize this document."484  YAML485  ```486487  ```python Python488  client = anthropic.Anthropic()489490  # Read the text file491  with open("document.txt") as f:492      text_content = f.read()493494  response = client.messages.create(495      model="claude-opus-5",496      max_tokens=1024,497      messages=[498          {499              "role": "user",500              "content": [501                  {502                      "type": "text",503                      "text": f"Here's the document content:\n\n{text_content}\n\nPlease summarize this document.",504                  }505              ],506          }507      ],508  )509510  for block in response.content:511      if block.type == "text":512          print(block.text)513  ```514515  ```typescript TypeScript516  import fs from "node:fs/promises";517  // ...518  const client = new Anthropic();519520  // Read the text file521  const textContent = await fs.readFile("document.txt", "utf-8");522523  const response = await client.messages.create({524    model: "claude-opus-5",525    max_tokens: 1024,526    messages: [527      {528        role: "user",529        content: [530          {531            type: "text",532            text: `Here's the document content:\n\n${textContent}\n\nPlease summarize this document.`533          }534        ]535      }536    ]537  });538539  const textBlock = response.content.find(540    (block): block is Anthropic.TextBlock => block.type === "text"541  );542  console.log(textBlock?.text);543  ```544545  ```csharp C#546  AnthropicClient client = new();547548  // Read the text file549  string textContent = await File.ReadAllTextAsync("document.txt");550551  var parameters = new MessageCreateParams552  {553      Model = Model.ClaudeOpus5,554      MaxTokens = 1024,555      Messages = [new()556      {557          Role = Role.User,558          Content = $"Here's the document content:\n\n{textContent}\n\nPlease summarize this document."559      }]560  };561562  var message = await client.Messages.Create(parameters);563  foreach (var block in message.Content)564  {565      if (block.TryPickText(out var textBlock))566      {567          Console.WriteLine(textBlock.Text);568      }569  }570  ```571572  ```go Go573  client := anthropic.NewClient()574575  // Read the text file576  textContent, err := os.ReadFile("document.txt")577  if err != nil {578  	log.Fatal(err)579  }580581  response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{582  	Model:     anthropic.ModelClaudeOpus5,583  	MaxTokens: 1024,584  	Messages: []anthropic.MessageParam{585  		anthropic.NewUserMessage(anthropic.NewTextBlock(586  			fmt.Sprintf("Here's the document content:\n\n%s\n\nPlease summarize this document.", string(textContent)),587  		)),588  	},589  })590  if err != nil {591  	log.Fatal(err)592  }593594  for _, block := range response.Content {595  	if textBlock, ok := block.AsAny().(anthropic.TextBlock); ok {596  		fmt.Println(textBlock.Text)597  	}598  }599  ```600601  ```java Java602  AnthropicClient client = AnthropicOkHttpClient.fromEnv();603604  // Read the text file605  String textContent = Files.readString(Path.of("document.txt"));606607  MessageCreateParams params = MessageCreateParams.builder()608      .model(Model.CLAUDE_OPUS_5)609      .maxTokens(1024L)610      .addUserMessage("Here's the document content:\n\n" + textContent + "\n\nPlease summarize this document.")611      .build();612613  Message response = client.messages().create(params);614  response.content().stream()615      .flatMap(block -> block.text().stream())616      .forEach(textBlock -> System.out.println(textBlock.text()));617  ```618619  ```php PHP620  $client = new Client();621622  // Read the text file623  $textContent = file_get_contents("document.txt");624625  $message = $client->messages->create(626      maxTokens: 1024,627      messages: [628          [629              'role' => 'user',630              'content' => [631                  [632                      'type' => 'text',633                      'text' => "Here's the document content:\n\n{$textContent}\n\nPlease summarize this document."634                  ]635              ]636          ]637      ],638      model: 'claude-opus-5',639  );640641  foreach ($message->content as $block) {642      if ($block->type === 'text') {643          echo $block->text, PHP_EOL;644      }645  }646  ```647648  ```ruby Ruby649  client = Anthropic::Client.new650651  # Read the text file652  text_content = File.read("document.txt")653654  message = client.messages.create(655    model: "claude-opus-5",656    max_tokens: 1024,657    messages: [658      {659        role: "user",660        content: [661          {662            type: "text",663            text: "Here's the document content:\n\n#{text_content}\n\nPlease summarize this document."664          }665        ]666      }667    ]668  )669670  message.content.each do |block|671    puts block.text if block.type == :text672  end673  ```674</CodeGroup>675676<Note>677  For .docx files containing images, convert them to PDF format first, then use [PDF support](https://platform.claude.com/docs/en/build-with-claude/pdf-support) to take advantage of the built-in image parsing. This allows using citations from the PDF document.678</Note>679680### Managing files681682#### List files683684Retrieve a list of your uploaded files. The endpoint is paginated: each request returns up to `limit` files (20 by default, and at most 1,000), and the response's `next_page` cursor fetches the next page when passed back as the `page` parameter. Files are ordered newest first. See the [List Files API reference](https://platform.claude.com/docs/en/api/files/list). The SDKs return the first page and provide auto-pagination helpers. The CLI example bounds the total with `--max-items`:685686<CodeGroup>687  ```bash cURL688  curl https://api.anthropic.com/v1/files \689    -H "x-api-key: $ANTHROPIC_API_KEY" \690    -H "anthropic-version: 2023-06-01"691  ```692693  ```bash CLI694  ant files list --max-items 10695  ```696697  ```python Python698  client = anthropic.Anthropic()699  files = client.files.list()700  print(files)701  ```702703  ```typescript TypeScript704  const client = new Anthropic();705  const files = await client.files.list();706  console.log(files);707  ```708709  ```csharp C#710  AnthropicClient client = new();711712  var files = await client.Files.List();713  Console.WriteLine(files);714  ```715716  ```go Go717  client := anthropic.NewClient()718719  files, err := client.Files.List(context.TODO(), anthropic.FileListParams{})720  if err != nil {721  	log.Fatal(err)722  }723  fmt.Println(files)724  ```725726  ```java Java727  import com.anthropic.models.files.FileListPage;728  // ...729  void main() {730      AnthropicClient client = AnthropicOkHttpClient.fromEnv();731732      FileListPage files = client.files().list();733      System.out.println(files);734  }735  ```736737  ```php PHP738  $client = new Client();739740  $files = $client->files->list();741  echo $files;742  ```743744  ```ruby Ruby745  client = Anthropic::Client.new746747  files = client.files.list748  puts files749  ```750</CodeGroup>751752To check a known set of files in one request instead of paging, pass up to 100 file IDs as `ids[]` query parameters. An `ids[]` request always returns a single page (`next_page` is `null`), and any ID that does not resolve to a file in your workspace is silently omitted from `data`; compare the returned IDs against the requested IDs to detect misses. `ids[]` cannot be combined with `page` or `limit`.753754#### Get file metadata755756Retrieve information about a specific file:757758<CodeGroup>759  ```bash cURL760  curl "https://api.anthropic.com/v1/files/$FILE_ID" \761    -H "x-api-key: $ANTHROPIC_API_KEY" \762    -H "anthropic-version: 2023-06-01"763  ```764765  ```bash CLI766  ant files retrieve-metadata \767    --file-id "$FILE_ID"768  ```769770  ```python Python771  file = client.files.retrieve_metadata(file_id)772  print(file)773  ```774775  ```typescript TypeScript776  const file = await client.files.retrieveMetadata(uploaded.id);777  console.log(file);778  ```779780  ```csharp C#781  var file = await client.Files.RetrieveMetadata(fileId);782  Console.WriteLine(file);783  ```784785  ```go Go786  metadata, err := client.Files.GetMetadata(context.TODO(), fileID, anthropic.FileGetMetadataParams{})787  if err != nil {788  	log.Fatal(err)789  }790791  fmt.Println(metadata)792  ```793794  ```java Java795  FileMetadata metadata = client.files().retrieveMetadata(fileId);796797  System.out.println(metadata);798  ```799800  ```php PHP801  $file = $client->files->retrieveMetadata($fileId);802  echo $file;803  ```804805  ```ruby Ruby806  file = client.files.retrieve_metadata(file_id)807  puts file808  ```809</CodeGroup>810811#### Delete a file812813Remove a file from your workspace:814815<CodeGroup>816  ```bash cURL817  curl -X DELETE "https://api.anthropic.com/v1/files/$FILE_ID" \818    -H "x-api-key: $ANTHROPIC_API_KEY" \819    -H "anthropic-version: 2023-06-01"820  ```821822  ```bash CLI823  ant files delete \824    --file-id "$FILE_ID"825  ```826827  ```python Python828  client.files.delete(file_id)829  ```830831  ```typescript TypeScript832  await client.files.delete(uploaded.id);833  ```834835  ```csharp C#836  await client.Files.Delete(fileId);837  ```838839  ```go Go840  _, err = client.Files.Delete(context.TODO(), fileID, anthropic.FileDeleteParams{})841  if err != nil {842  	log.Fatal(err)843  }844  ```845846  ```java Java847  client.files().delete(fileId);848  ```849850  ```php PHP851  $client->files->delete($fileId);852  ```853854  ```ruby Ruby855  client.files.delete(file_id)856  ```857</CodeGroup>858859### Downloading a file860861Download files that were created by [skills](https://platform.claude.com/docs/en/build-with-claude/skills-guide) or the [code execution tool](https://platform.claude.com/docs/en/agents-and-tools/tool-use/code-execution-tool). Files you upload cannot be downloaded. The `file_id` of a generated file appears in the [`bash_code_execution_tool_result` content block](https://platform.claude.com/docs/en/agents-and-tools/tool-use/code-execution-tool#retrieve-generated-files) of the Messages response that created it:862863<CodeGroup>864  ```bash cURL865  curl -X GET "https://api.anthropic.com/v1/files/$FILE_ID/content" \866    -H "x-api-key: $ANTHROPIC_API_KEY" \867    -H "anthropic-version: 2023-06-01" \868    --output downloaded_file.txt869  ```870871  ```bash CLI872  ant files download \873    --file-id "$FILE_ID" \874    --output downloaded_file.txt875  ```876877  ```python Python878  file_content = client.files.download(file_id)879880  file_content.write_to_file("downloaded_file.txt")881  ```882883  ```typescript TypeScript884  const content = await client.files.download(uploaded.id);885886  const bytes = Buffer.from(await content.arrayBuffer());887  await fsp.writeFile("downloaded_file.txt", bytes);888  ```889890  ```csharp C#891  using var fileContent = await client.Files.Download(fileId);892  await using var source = await fileContent.ReadAsStream();893  await using var destination = File.Create("downloaded_file.txt");894  await source.CopyToAsync(destination);895  ```896897  ```go Go898  func downloadFile(client anthropic.Client, fileID string) error {899  	resp, err := client.Files.Download(context.TODO(), fileID, anthropic.FileDownloadParams{})900  	if err != nil {901  		return err902  	}903  	defer resp.Body.Close()904905  	out, err := os.Create("downloaded_file.txt")906  	if err != nil {907  		return err908  	}909  	defer out.Close()910911  	_, err = io.Copy(out, resp.Body)912  	return err913  }914915  ```916917  ```java Java918  try (HttpResponse response = client.files().download(fileId)) {919      try (InputStream body = response.body()) {920          Files.copy(body, Path.of("downloaded_file.txt"),921              StandardCopyOption.REPLACE_EXISTING);922      }923  }924  ```925926  ```php PHP927  $fileContent = $client->files->download($fileId);928929  file_put_contents('downloaded_file.txt', $fileContent);930  ```931932  ```ruby Ruby933  file_content = client.files.download(file_id)934935  File.binwrite("downloaded_file.txt", file_content.read)936  ```937</CodeGroup>938939<Note>940  A file is downloadable only when its metadata shows `"downloadable": true`, which is the case for files created by skills or the code execution tool. Downloading a file you uploaded returns a 400 error.941</Note>942943On the Claude API, supported image, video, and audio files that Claude produces with the code execution tool, including files created by skills, carry signed C2PA Content Credentials when you download them. See [Content Credentials on generated files](https://platform.claude.com/docs/en/agents-and-tools/tool-use/code-execution-tool#content-credentials-on-generated-files) for what the credential contains and how to verify it.944945## File storage and limits946947### Storage limits948949* **Maximum file size:** 500 MB per file950* **Total storage:** 1 TB per organization951952### File lifecycle953954* Files are scoped to the workspace they were uploaded in. Any request in the same workspace can reference them; never accept file IDs from untrusted sources (see the [workspace access warning](https://platform.claude.com/docs/en/build-with-claude/files#workspace-scoped-access))955* Files cannot be modified or renamed after upload. To change a file's content, upload a new file and delete the old one956* Files persist until you delete them with the `DELETE /v1/files/{file_id}` endpoint or they reach their `expires_at`957* Deleted files cannot be recovered958* Files are inaccessible through the API shortly after deletion, but they may persist in active Messages API calls and associated tool uses959* Files that users delete will be deleted in accordance with Anthropic's [data retention policy](https://privacy.claude.com/en/articles/7996866-how-long-do-you-store-my-organization-s-data). For ZDR eligibility across all features, see [API and data retention](https://platform.claude.com/docs/en/manage-claude/api-and-data-retention)960961### File expiration962963To have a file expire automatically, include an `expires_in_seconds` form field when you upload it. The value is an integer number of seconds between 3,600 (1 hour) and 7,776,000 (90 days). The resulting `expires_at` timestamp (RFC 3339) appears on every file response and is `null` for files uploaded without an expiration. Expiration is set once at upload and cannot be changed.964965When a file reaches its `expires_at`:966967* Downloading its content (`GET /v1/files/{file_id}/content`) returns a 404 error968* A Messages request that references the file fails before inference969* Its metadata (`GET /v1/files/{file_id}`) remains readable for up to 30 days, with `expires_at` in the past970* It continues to appear in list responses during that window; compare `expires_at` to the current time to filter expired files971972Deleting an expired file with `DELETE /v1/files/{file_id}` removes its metadata immediately instead of waiting for the 30-day window to elapse.973974<Note>975  Expiration is a lifecycle feature, not a guaranteed-deletion control. After `expires_at`, file content is no longer retrievable through the API and is released from your storage quota; the underlying content may be retained for a limited period thereafter for safety review before permanent deletion, and file metadata remains visible for up to 30 days after expiration. To remove a file before its scheduled expiration, use `DELETE /v1/files/{file_id}`.976</Note>977978### Audit logging979980If your organization has the [Compliance API](https://platform.claude.com/docs/en/manage-claude/compliance-api) enabled, its [Activity Feed](https://platform.claude.com/docs/en/manage-claude/compliance-activity-feed) records Files API operations made with a Claude API key or from the Claude Console: each upload (`POST /v1/files`), content download (`GET /v1/files/{file_id}/content`), and deletion (`DELETE /v1/files/{file_id}`) appears as a `platform_file_uploaded`, `platform_file_content_downloaded`, or `platform_file_deleted` activity. Listing files and retrieving file metadata are not recorded. Operations that occur while the Compliance API is off are not recorded and cannot be recovered later, so [set up the Compliance API](https://platform.claude.com/docs/en/manage-claude/compliance-api-access) before you rely on this audit trail. On [Claude Platform on AWS](https://platform.claude.com/docs/en/build-with-claude/claude-platform-on-aws#monitoring-and-logging), audit file operations with AWS CloudTrail data events instead.981982## Migrate from `files-api-2025-04-14`983984The Files API is out of beta and needs no beta header. Migrating off `files-api-2025-04-14` is optional: requests that still send it keep working and keep returning the beta response shapes, so an existing integration keeps working until you change it. Removing the header switches those requests to the shapes documented on this page:985986|                                          | With `files-api-2025-04-14`             | Without the header                                                           |987| ---------------------------------------- | --------------------------------------- | ---------------------------------------------------------------------------- |988| List response                            | `{ data, has_more, first_id, last_id }` | `{ data, next_page }`; pass `next_page` back as the `page` query parameter   |989| List cursors                             | `before_id`, `after_id`                 | `page`, or up to 100 `ids[]` (`before_id` and `after_id` return a 400 error) |990| `expires_at` on file objects             | Not returned                            | Always present; `null` when the file has no expiration                       |991| `Content-Type` on the uploaded file part | Required                                | Optional; the type is detected when omitted                                  |992993To migrate:9949951. **Remove the beta header.** Drop `anthropic-beta: files-api-2025-04-14` from your requests. In the SDKs, call `client.files` instead of `client.beta.files`; keeping `client.beta.files` works only on the [SDK releases that no longer send the header](https://platform.claude.com/docs/en/build-with-claude/files#sdk-beta-namespace). Earlier releases send it from `client.beta.files` even with no `betas` argument.9962. **Update pagination.** Replace `after_id`/`before_id` loops with the `page`/`next_page` cursor, or use the SDK auto-pagination helpers shown in [Managing files](https://platform.claude.com/docs/en/build-with-claude/files#managing-files).9973. **Read `expires_at`.** The field appears only without the header; `null` means the file has no expiration (see [File expiration](https://platform.claude.com/docs/en/build-with-claude/files#file-expiration)).998999### SDK beta namespace10001001Starting with Python SDK 1.2.0, TypeScript SDK 0.122.0, Go SDK 1.68.0, Java SDK 2.59.0, Ruby SDK 1.67.0, and C# SDK 12.44.0, `client.beta.files` no longer sends `files-api-2025-04-14` and returns the same shapes as `client.files`, with `Beta`-prefixed type names. It accepts a `betas` argument for Files features that are still in beta, such as `scope_id` filtering under a [Managed Agents](https://platform.claude.com/docs/en/managed-agents/files) beta header. Earlier SDK releases are typed to the beta shapes; if you depend on those types, stay on an earlier release until you migrate.10021003Requests that carry `anthropic-beta: managed-agents-2026-04-01` without `files-api-2025-04-14` receive the shapes on this page with one compatibility affordance on `GET /v1/files`: `before_id` and `after_id` are still accepted (not combinable with `page` or `ids[]`), and the list response includes `has_more`, `first_id`, and `last_id` alongside `next_page`. Later Managed Agents beta versions receive the plain shape.10041005## Error handling10061007Common errors when using the Files API include:10081009* **File not found (404):** The specified `file_id` doesn't exist or you don't have access to it1010* **Invalid file type (400):** The file type doesn't match the content block type (for example, using an image file in a document block)1011* **Not downloadable (400):** Files you upload have `"downloadable": false` and cannot be downloaded. Only files created by skills or the code execution tool can be downloaded1012* **Exceeds context window size (400):** The file is larger than the context window size (for example, using a 500 MB plain text file in a `/v1/messages` request)1013* **Invalid filename (400):** The file name doesn't meet the length requirements (1-255 characters) or contains forbidden characters (`<`, `>`, `:`, `"`, `|`, `?`, `*`, `\`, `/`, or Unicode characters 0-31)1014* **File too large (413):** File exceeds the 500 MB limit1015* **Storage limit exceeded (400):** Your organization has reached the 1 TB storage limit10161017```json Output1018{1019  "type": "error",1020  "error": {1021    "type": "not_found_error",1022    "message": "File `file_011CNha8iCJcU1wXNR6q4V8w` not found."1023  },1024  "request_id": "req_011CQFYcrRp7mCHLDsAYT8Qt"1025}1026```10271028## Usage and billing10291030Files API operations are free:10311032* Uploading files1033* Downloading files1034* Listing files1035* Getting file metadata1036* Deleting files10371038File content used in Messages requests is priced as input tokens.10391040### Rate limits10411042File-related API calls are limited to approximately 500 requests per minute. To request a higher limit, [contact sales](mailto:sales@anthropic.com).10431044## Next steps10451046<CardGroup cols={3}>1047  <Card title="PDF support" icon="file" href="https://platform.claude.com/docs/en/build-with-claude/pdf-support">1048    Process PDFs with Claude. Extract text, analyze charts, and understand visual content from your documents.1049  </Card>10501051  <Card title="Code execution tool" icon="terminal" href="https://platform.claude.com/docs/en/agents-and-tools/tool-use/code-execution-tool">1052    Run Python and bash code in a sandboxed container to analyze data, generate files, and iterate on solutions.1053  </Card>10541055  <Card title="Vision" icon="image" href="https://platform.claude.com/docs/en/build-with-claude/vision">1056    Process and analyze visual input and generate text and code from images.1057  </Card>1058</CardGroup>1059
Files main
Menu

Theme