claude-api 0.5.1

Type-safe Rust client for the Anthropic API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
//! The async `Files<'a>` namespace.

#![cfg(feature = "async")]

use std::path::Path;

use bytes::Bytes;
use futures_util::stream::TryStreamExt;
use tokio::io::{AsyncRead, AsyncWrite};
use tokio_util::io::{ReaderStream, StreamReader};

use crate::client::Client;
use crate::error::{Error, Result};
use crate::pagination::Paginated;

use super::types::{FileDeleted, FileMetadata, ListFilesParams};

/// Beta version tag attached to every Files-API request.
const FILES_BETA: &[&str] = &["files-api-2025-04-14"];

/// Namespace handle for the Files API.
pub struct Files<'a> {
    client: &'a Client,
}

impl<'a> Files<'a> {
    pub(crate) fn new(client: &'a Client) -> Self {
        Self { client }
    }

    /// Upload a file from disk.
    ///
    /// Streams the file body through the request without buffering it in
    /// memory; suitable for large PDFs.
    ///
    /// `media_type` defaults to `application/octet-stream`. The filename is
    /// taken from the path's file name component.
    pub async fn upload_path(&self, path: impl AsRef<Path>) -> Result<FileMetadata> {
        let path = path.as_ref();
        let filename = path
            .file_name()
            .and_then(|s| s.to_str())
            .ok_or_else(|| {
                Error::InvalidConfig(format!("invalid filename in path {}", path.display()))
            })?
            .to_owned();
        let media_type = guess_media_type(&filename).unwrap_or("application/octet-stream");
        let file = tokio::fs::File::open(path).await?;
        self.upload_stream(file, filename, media_type).await
    }

    /// Upload from any [`AsyncRead`] source. The body is streamed; not
    /// buffered. Retries are *not* applied to uploads -- the source is
    /// consumed.
    pub async fn upload_stream<R>(
        &self,
        reader: R,
        filename: impl Into<String>,
        media_type: impl Into<String>,
    ) -> Result<FileMetadata>
    where
        R: AsyncRead + Send + Sync + 'static,
    {
        let filename = filename.into();
        let media_type = media_type.into();
        let stream = ReaderStream::new(Box::pin(reader));
        let body = reqwest::Body::wrap_stream(stream);
        let part = reqwest::multipart::Part::stream(body)
            .file_name(filename)
            .mime_str(&media_type)
            .map_err(|e| Error::InvalidConfig(format!("invalid media_type for upload: {e}")))?;
        self.upload_with_part(part).await
    }

    /// Upload from a `Bytes` buffer (or anything that converts to `Bytes`).
    /// Suitable for small payloads where streaming is overkill.
    pub async fn upload_bytes(
        &self,
        bytes: impl Into<Bytes>,
        filename: impl Into<String>,
        media_type: impl Into<String>,
    ) -> Result<FileMetadata> {
        let filename = filename.into();
        let media_type = media_type.into();
        let part = reqwest::multipart::Part::bytes(bytes.into().to_vec())
            .file_name(filename)
            .mime_str(&media_type)
            .map_err(|e| Error::InvalidConfig(format!("invalid media_type for upload: {e}")))?;
        self.upload_with_part(part).await
    }

    async fn upload_with_part(&self, part: reqwest::multipart::Part) -> Result<FileMetadata> {
        let form = reqwest::multipart::Form::new().part("file", part);
        // No retry: multipart bodies built from streaming sources are
        // single-use. Users who need retry should wrap their own loop
        // around upload_path / upload_bytes.
        let builder = self
            .client
            .request_builder(reqwest::Method::POST, "/v1/files")
            .multipart(form);
        self.client.execute(builder, FILES_BETA).await
    }

    /// Fetch metadata for a single file by ID.
    pub async fn get(&self, id: &str) -> Result<FileMetadata> {
        let path = format!("/v1/files/{id}");
        self.client
            .execute_with_retry(
                || self.client.request_builder(reqwest::Method::GET, &path),
                FILES_BETA,
            )
            .await
    }

    /// Fetch one page of file metadata.
    pub async fn list(&self, params: ListFilesParams) -> Result<Paginated<FileMetadata>> {
        let params_ref = &params;
        self.client
            .execute_with_retry(
                || {
                    self.client
                        .request_builder(reqwest::Method::GET, "/v1/files")
                        .query(params_ref)
                },
                FILES_BETA,
            )
            .await
    }

    /// Fetch every file's metadata, transparently paging.
    pub async fn list_all(&self) -> Result<Vec<FileMetadata>> {
        let mut all = Vec::new();
        let mut params = ListFilesParams::default();
        loop {
            let page = self.list(params.clone()).await?;
            let next_cursor = page.next_after().map(str::to_owned);
            all.extend(page.data);
            match next_cursor {
                Some(cursor) => params.after_id = Some(cursor),
                None => break,
            }
        }
        Ok(all)
    }

    /// Delete a file by ID. Returns the deletion confirmation.
    pub async fn delete(&self, id: &str) -> Result<FileDeleted> {
        let path = format!("/v1/files/{id}");
        self.client
            .execute_with_retry(
                || self.client.request_builder(reqwest::Method::DELETE, &path),
                FILES_BETA,
            )
            .await
    }

    /// Download a file's bytes into memory. Suitable for small files; for
    /// streaming to disk or a network sink, use [`Self::download_to`].
    pub async fn download(&self, id: &str) -> Result<Bytes> {
        let path = format!("/v1/files/{id}/content");
        let response = self
            .client
            .execute_streaming(
                self.client.request_builder(reqwest::Method::GET, &path),
                FILES_BETA,
            )
            .await?;
        Ok(response.bytes().await?)
    }

    /// Stream a file's bytes into any [`AsyncWrite`] sink. Returns the
    /// total number of bytes written.
    pub async fn download_to<W>(&self, id: &str, writer: &mut W) -> Result<u64>
    where
        W: AsyncWrite + Unpin,
    {
        let path = format!("/v1/files/{id}/content");
        let response = self
            .client
            .execute_streaming(
                self.client.request_builder(reqwest::Method::GET, &path),
                FILES_BETA,
            )
            .await?;
        let stream = response
            .bytes_stream()
            .map_err(|e| std::io::Error::other(e.to_string()));
        let mut reader = StreamReader::new(stream);
        let copied = tokio::io::copy(&mut reader, writer).await?;
        Ok(copied)
    }
}

/// Best-effort MIME type from a filename extension. Returns `None` for
/// extensions not in the small built-in table; callers can still pass any
/// `media_type` explicitly via [`Files::upload_stream`] / [`Files::upload_bytes`].
fn guess_media_type(filename: &str) -> Option<&'static str> {
    let ext = filename.rsplit('.').next()?.to_ascii_lowercase();
    Some(match ext.as_str() {
        "pdf" => "application/pdf",
        "txt" | "md" | "log" => "text/plain",
        "json" => "application/json",
        "csv" => "text/csv",
        "html" | "htm" => "text/html",
        "xml" => "application/xml",
        "png" => "image/png",
        "jpg" | "jpeg" => "image/jpeg",
        "gif" => "image/gif",
        "webp" => "image/webp",
        _ => return None,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use pretty_assertions::assert_eq;
    use serde_json::json;
    use wiremock::matchers::{header_exists, method, path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    fn client_for(mock: &MockServer) -> Client {
        Client::builder()
            .api_key("sk-ant-test")
            .base_url(mock.uri())
            .build()
            .unwrap()
    }

    fn file_metadata_json(id: &str) -> serde_json::Value {
        json!({
            "id": id,
            "type": "file",
            "filename": "test.pdf",
            "mime_type": "application/pdf",
            "size_bytes": 4,
            "created_at": "2026-04-30T00:00:00Z",
            "downloadable": true
        })
    }

    #[tokio::test]
    async fn upload_bytes_sends_multipart_and_decodes_metadata() {
        let mock = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/v1/files"))
            .and(header_exists("anthropic-beta"))
            .respond_with(ResponseTemplate::new(200).set_body_json(file_metadata_json("file_b1")))
            .mount(&mock)
            .await;

        let client = client_for(&mock);
        let meta = client
            .files()
            .upload_bytes(Bytes::from_static(b"abcd"), "test.pdf", "application/pdf")
            .await
            .unwrap();
        assert_eq!(meta.id, "file_b1");
        assert_eq!(meta.size_bytes, 4);

        // Verify the beta header is the Files-API tag.
        let req = &mock.received_requests().await.unwrap()[0];
        let beta = req.headers.get("anthropic-beta").unwrap().to_str().unwrap();
        assert!(beta.contains("files-api-"), "{beta}");
    }

    #[tokio::test]
    async fn upload_path_streams_real_file_from_disk() {
        let mock = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/v1/files"))
            .respond_with(ResponseTemplate::new(200).set_body_json(file_metadata_json("file_p1")))
            .mount(&mock)
            .await;

        let dir = std::env::temp_dir();
        let path = dir.join(format!("claude_api_test_{}.txt", std::process::id()));
        std::fs::write(&path, b"hello from disk").unwrap();

        let client = client_for(&mock);
        let meta = client.files().upload_path(&path).await.unwrap();
        assert_eq!(meta.id, "file_p1");

        std::fs::remove_file(&path).ok();
    }

    #[tokio::test]
    async fn upload_stream_accepts_any_async_read() {
        let mock = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/v1/files"))
            .respond_with(ResponseTemplate::new(200).set_body_json(file_metadata_json("file_s1")))
            .mount(&mock)
            .await;

        let client = client_for(&mock);
        // &[u8] satisfies AsyncRead through tokio's blanket impl, but we need
        // owned + 'static. Wrap in a Cursor over Vec<u8>.
        let reader = std::io::Cursor::new(b"streamed bytes".to_vec());
        let meta = client
            .files()
            .upload_stream(reader, "stream.txt", "text/plain")
            .await
            .unwrap();
        assert_eq!(meta.id, "file_s1");
    }

    #[tokio::test]
    async fn get_returns_metadata_for_id() {
        let mock = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/v1/files/file_g1"))
            .and(header_exists("anthropic-beta"))
            .respond_with(ResponseTemplate::new(200).set_body_json(file_metadata_json("file_g1")))
            .mount(&mock)
            .await;

        let client = client_for(&mock);
        let meta = client.files().get("file_g1").await.unwrap();
        assert_eq!(meta.id, "file_g1");
    }

    #[tokio::test]
    async fn list_returns_paginated_envelope() {
        let mock = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/v1/files"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "data": [file_metadata_json("file_l1"), file_metadata_json("file_l2")],
                "has_more": false,
                "first_id": "file_l1",
                "last_id": "file_l2"
            })))
            .mount(&mock)
            .await;

        let client = client_for(&mock);
        let page = client
            .files()
            .list(ListFilesParams::default())
            .await
            .unwrap();
        assert_eq!(page.data.len(), 2);
    }

    #[tokio::test]
    async fn delete_returns_typed_confirmation() {
        let mock = MockServer::start().await;
        Mock::given(method("DELETE"))
            .and(path("/v1/files/file_d1"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "id": "file_d1",
                "type": "file_deleted"
            })))
            .mount(&mock)
            .await;

        let client = client_for(&mock);
        let confirm = client.files().delete("file_d1").await.unwrap();
        assert_eq!(confirm.id, "file_d1");
        assert_eq!(confirm.kind, "file_deleted");
    }

    #[tokio::test]
    async fn download_returns_file_bytes() {
        let mock = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/v1/files/file_dl1/content"))
            .respond_with(ResponseTemplate::new(200).set_body_bytes(b"file payload bytes".to_vec()))
            .mount(&mock)
            .await;

        let client = client_for(&mock);
        let bytes = client.files().download("file_dl1").await.unwrap();
        assert_eq!(&bytes[..], b"file payload bytes");
    }

    #[tokio::test]
    async fn download_to_streams_into_async_write() {
        let mock = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/v1/files/file_dl2/content"))
            .respond_with(ResponseTemplate::new(200).set_body_bytes(b"streamed download".to_vec()))
            .mount(&mock)
            .await;

        let client = client_for(&mock);
        let mut sink: Vec<u8> = Vec::new();
        let bytes_written = client
            .files()
            .download_to("file_dl2", &mut sink)
            .await
            .unwrap();
        assert_eq!(bytes_written, b"streamed download".len() as u64);
        assert_eq!(&sink[..], b"streamed download");
    }

    #[tokio::test]
    async fn download_propagates_404_with_request_id() {
        let mock = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/v1/files/missing/content"))
            .respond_with(
                ResponseTemplate::new(404)
                    .insert_header("request-id", "req_404")
                    .set_body_json(json!({
                        "type": "error",
                        "error": {"type": "not_found_error", "message": "no such file"}
                    })),
            )
            .mount(&mock)
            .await;

        let client = client_for(&mock);
        let err = client.files().download("missing").await.unwrap_err();
        assert_eq!(err.status(), Some(http::StatusCode::NOT_FOUND));
        assert_eq!(err.request_id(), Some("req_404"));
    }

    #[test]
    fn guess_media_type_handles_common_extensions() {
        assert_eq!(guess_media_type("doc.pdf"), Some("application/pdf"));
        assert_eq!(guess_media_type("notes.MD"), Some("text/plain"));
        assert_eq!(guess_media_type("photo.jpg"), Some("image/jpeg"));
        assert_eq!(guess_media_type("photo.JPEG"), Some("image/jpeg"));
        assert_eq!(guess_media_type("data.unknown"), None);
        assert_eq!(guess_media_type("noext"), None);
    }
}