Skip to main content

rust_claude_sdk/
files.rs

1//! Files API: upload once, then refer to the file by id from `document` and `image` blocks
2//! (`DocumentSource::File`, `ImageSource::File`), and download what code execution wrote.
3use reqwest::Method;
4use serde::{Deserialize, Serialize};
5use serde_json::{Map, Value};
6
7use crate::client::{CallOptions, Client, Payload};
8use crate::error::Error;
9use crate::page::{Deleted, ListParams, Page};
10
11#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
12pub struct FileMetadata {
13    pub id: String,
14    #[serde(default)]
15    pub filename: String,
16    #[serde(default)]
17    pub mime_type: String,
18    #[serde(default)]
19    pub size_bytes: u64,
20    /// RFC 3339.
21    #[serde(default)]
22    pub created_at: String,
23    /// Only files created by tools (code execution, skills) can be downloaded.
24    #[serde(default)]
25    pub downloadable: bool,
26    /// `type` and anything else.
27    #[serde(flatten)]
28    pub extra: Map<String, Value>,
29}
30
31impl Client {
32    /// `POST /v1/files` (multipart). The block that uses the file must match its type:
33    /// `document` for PDF and plain text, `image` for images.
34    pub async fn upload_file(&self, filename: &str, mime_type: &str, data: &[u8]) -> Result<FileMetadata, Error> {
35        self.call(Method::POST, &["v1", "files"], &[], Payload::File { filename, mime_type, data }, &[], CallOptions::default()).await
36    }
37
38    /// `GET /v1/files`: one page, newest first.
39    pub async fn list_files(&self, params: &ListParams) -> Result<Page<FileMetadata>, Error> {
40        self.call(Method::GET, &["v1", "files"], &params.query(), Payload::Empty, &[], CallOptions::default()).await
41    }
42
43    /// `GET /v1/files/{id}`.
44    pub async fn file(&self, id: &str) -> Result<FileMetadata, Error> {
45        self.call(Method::GET, &["v1", "files", id], &[], Payload::Empty, &[], CallOptions::default()).await
46    }
47
48    /// `GET /v1/files/{id}/content`: the file's bytes (downloadable files only).
49    pub async fn download_file(&self, id: &str) -> Result<Vec<u8>, Error> {
50        self.call_bytes(Method::GET, &["v1", "files", id, "content"], &[], Payload::Empty, &[], CallOptions::default()).await
51    }
52
53    /// `DELETE /v1/files/{id}`.
54    pub async fn delete_file(&self, id: &str) -> Result<Deleted, Error> {
55        self.call(Method::DELETE, &["v1", "files", id], &[], Payload::Empty, &[], CallOptions::default()).await
56    }
57}