firecrawl 2.3.1

Official Rust SDK for Firecrawl API v2.
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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
//! Batch scrape endpoint for Firecrawl API v2.

use serde::{Deserialize, Serialize};

use crate::client::Client;
use crate::scrape::ScrapeOptions;
use crate::types::{CrawlErrorsResponse, Document, JobStatus, WebhookConfig};
use crate::FirecrawlError;

/// Options for batch scraping.
#[serde_with::skip_serializing_none]
#[derive(Deserialize, Serialize, Debug, Default, Clone)]
#[serde(rename_all = "camelCase")]
pub struct BatchScrapeOptions {
    /// Scrape options to apply to all URLs.
    #[serde(flatten)]
    pub options: Option<ScrapeOptions>,

    /// Webhook configuration for job notifications.
    pub webhook: Option<WebhookConfig>,

    /// ID of an existing batch job to append URLs to.
    pub append_to_id: Option<String>,

    /// Whether to ignore invalid URLs instead of failing.
    #[serde(rename = "ignoreInvalidURLs")]
    pub ignore_invalid_urls: Option<bool>,

    /// Maximum concurrent requests.
    pub max_concurrency: Option<u32>,

    /// Enable zero data retention mode.
    pub zero_data_retention: Option<bool>,

    /// Idempotency key for the request.
    #[serde(skip)]
    pub idempotency_key: Option<String>,

    /// Integration identifier for tracking.
    pub integration: Option<String>,

    /// Poll interval for synchronous batch scrape (milliseconds).
    #[serde(skip)]
    pub poll_interval: Option<u64>,
}

/// Request body for batch scrape endpoint.
#[derive(Deserialize, Serialize, Debug, Default)]
#[serde(rename_all = "camelCase")]
struct BatchScrapeRequest {
    urls: Vec<String>,
    #[serde(flatten)]
    options: BatchScrapeOptions,
}

/// Response from starting a batch scrape job.
#[derive(Deserialize, Serialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct BatchScrapeResponse {
    /// Whether the request was successful.
    pub success: bool,
    /// The batch scrape job ID.
    pub id: String,
    /// URL to check the batch scrape status.
    pub url: String,
    /// URLs that were invalid and ignored.
    #[serde(rename = "invalidURLs")]
    pub invalid_urls: Option<Vec<String>>,
}

/// Status of a batch scrape job.
#[serde_with::skip_serializing_none]
#[derive(Deserialize, Serialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct BatchScrapeJob {
    /// Current status of the batch scrape job.
    pub status: JobStatus,
    /// Number of URLs completed.
    pub completed: u32,
    /// Total number of URLs to scrape.
    pub total: u32,
    /// Credits used by the batch scrape.
    pub credits_used: Option<u32>,
    /// Expiry time of the batch data.
    pub expires_at: Option<String>,
    /// URL for the next page of results.
    pub next: Option<String>,
    /// Scraped documents.
    pub data: Vec<Document>,
}

impl Client {
    /// Starts a batch scrape job asynchronously.
    ///
    /// Returns immediately with a job ID that can be used to check status.
    ///
    /// # Arguments
    ///
    /// * `urls` - List of URLs to scrape.
    /// * `options` - Optional batch scrape configuration.
    ///
    /// # Returns
    ///
    /// A `BatchScrapeResponse` containing the job ID.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use firecrawl::{Client, BatchScrapeOptions};
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let client = Client::new("your-api-key")?;
    ///
    ///     let urls = vec![
    ///         "https://example.com".to_string(),
    ///         "https://example.org".to_string(),
    ///     ];
    ///
    ///     let response = client.start_batch_scrape(urls, None).await?;
    ///     println!("Batch job started: {}", response.id);
    ///
    ///     // Check status later
    ///     let status = client.get_batch_scrape_status(&response.id).await?;
    ///     println!("Completed: {}/{}", status.completed, status.total);
    ///
    ///     Ok(())
    /// }
    /// ```
    pub async fn start_batch_scrape(
        &self,
        urls: Vec<String>,
        options: impl Into<Option<BatchScrapeOptions>>,
    ) -> Result<BatchScrapeResponse, FirecrawlError> {
        let options = options.into().unwrap_or_default();
        let body = BatchScrapeRequest {
            urls,
            options: options.clone(),
        };

        let headers = self.prepare_headers(options.idempotency_key.as_ref());

        let response = self
            .client
            .post(self.url("/batch/scrape"))
            .headers(headers)
            .json(&body)
            .send()
            .await
            .map_err(|e| FirecrawlError::HttpError("Starting batch scrape".to_string(), e))?;

        self.handle_response(response, "start batch scrape").await
    }

    /// Gets the status of a batch scrape job.
    ///
    /// If the job is completed, this will automatically fetch all pages of results.
    ///
    /// # Arguments
    ///
    /// * `id` - The batch scrape job ID.
    ///
    /// # Returns
    ///
    /// A `BatchScrapeJob` containing the current status and any available documents.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use firecrawl::Client;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let client = Client::new("your-api-key")?;
    ///
    ///     let status = client.get_batch_scrape_status("job-id").await?;
    ///     println!("Status: {:?}", status.status);
    ///     println!("Completed: {}/{}", status.completed, status.total);
    ///     println!("Documents: {}", status.data.len());
    ///
    ///     Ok(())
    /// }
    /// ```
    pub async fn get_batch_scrape_status(
        &self,
        id: impl AsRef<str>,
    ) -> Result<BatchScrapeJob, FirecrawlError> {
        let response = self
            .client
            .get(self.url(&format!("/batch/scrape/{}", id.as_ref())))
            .headers(self.prepare_headers(None))
            .send()
            .await
            .map_err(|e| {
                FirecrawlError::HttpError(
                    format!("Checking batch scrape status {}", id.as_ref()),
                    e,
                )
            })?;

        let mut status: BatchScrapeJob = self
            .handle_response(response, format!("batch scrape status {}", id.as_ref()))
            .await?;

        // Auto-paginate if completed
        if status.status == JobStatus::Completed {
            while let Some(next) = status.next.take() {
                let next_status = self.get_batch_scrape_status_next(&next).await?;
                status.data.extend(next_status.data);
                status.next = next_status.next;
            }
        }

        Ok(status)
    }

    /// Fetches the next page of batch scrape results.
    async fn get_batch_scrape_status_next(
        &self,
        next: &str,
    ) -> Result<BatchScrapeJob, FirecrawlError> {
        let response = self
            .client
            .get(next)
            .headers(self.prepare_headers(None))
            .send()
            .await
            .map_err(|e| {
                FirecrawlError::HttpError(format!("Paginating batch scrape at {}", next), e)
            })?;

        self.handle_response(response, "batch scrape pagination")
            .await
    }

    /// Scrapes multiple URLs and waits for completion.
    ///
    /// This method starts a batch scrape and polls until it completes or fails.
    ///
    /// # Arguments
    ///
    /// * `urls` - List of URLs to scrape.
    /// * `options` - Optional batch scrape configuration.
    ///
    /// # Returns
    ///
    /// A `BatchScrapeJob` containing all scraped documents.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use firecrawl::{Client, BatchScrapeOptions, ScrapeOptions, Format};
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let client = Client::new("your-api-key")?;
    ///
    ///     let urls = vec![
    ///         "https://example.com/page1".to_string(),
    ///         "https://example.com/page2".to_string(),
    ///         "https://example.com/page3".to_string(),
    ///     ];
    ///
    ///     let options = BatchScrapeOptions {
    ///         options: Some(ScrapeOptions {
    ///             formats: Some(vec![Format::Markdown, Format::Links]),
    ///             ..Default::default()
    ///         }),
    ///         ignore_invalid_urls: Some(true),
    ///         poll_interval: Some(3000),
    ///         ..Default::default()
    ///     };
    ///
    ///     let result = client.batch_scrape(urls, options).await?;
    ///     println!("Scraped {} pages", result.data.len());
    ///
    ///     for doc in result.data {
    ///         println!("URL: {:?}", doc.metadata.and_then(|m| m.source_url));
    ///     }
    ///
    ///     Ok(())
    /// }
    /// ```
    pub async fn batch_scrape(
        &self,
        urls: Vec<String>,
        options: impl Into<Option<BatchScrapeOptions>>,
    ) -> Result<BatchScrapeJob, FirecrawlError> {
        let options = options.into().unwrap_or_default();
        let poll_interval = options.poll_interval.unwrap_or(2000);

        let response = self.start_batch_scrape(urls, options).await?;
        self.wait_for_batch_scrape(&response.id, poll_interval)
            .await
    }

    /// Waits for a batch scrape job to complete.
    async fn wait_for_batch_scrape(
        &self,
        id: &str,
        poll_interval: u64,
    ) -> Result<BatchScrapeJob, FirecrawlError> {
        loop {
            let status = self.get_batch_scrape_status(id).await?;

            match status.status {
                JobStatus::Completed => return Ok(status),
                JobStatus::Scraping => {
                    tokio::time::sleep(tokio::time::Duration::from_millis(poll_interval)).await;
                }
                JobStatus::Failed => {
                    return Err(FirecrawlError::JobFailed(
                        "Batch scrape job failed".to_string(),
                        JobStatus::Failed,
                    ));
                }
                JobStatus::Cancelled => {
                    return Err(FirecrawlError::JobFailed(
                        "Batch scrape job was cancelled".to_string(),
                        JobStatus::Cancelled,
                    ));
                }
            }
        }
    }

    /// Gets errors from a batch scrape job.
    ///
    /// # Arguments
    ///
    /// * `id` - The batch scrape job ID.
    ///
    /// # Returns
    ///
    /// A `CrawlErrorsResponse` containing error details.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use firecrawl::Client;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let client = Client::new("your-api-key")?;
    ///
    ///     let errors = client.get_batch_scrape_errors("job-id").await?;
    ///     for error in errors.errors {
    ///         println!("Error on {}: {}", error.url, error.error);
    ///     }
    ///
    ///     Ok(())
    /// }
    /// ```
    pub async fn get_batch_scrape_errors(
        &self,
        id: impl AsRef<str>,
    ) -> Result<CrawlErrorsResponse, FirecrawlError> {
        let response = self
            .client
            .get(self.url(&format!("/batch/scrape/{}/errors", id.as_ref())))
            .headers(self.prepare_headers(None))
            .send()
            .await
            .map_err(|e| {
                FirecrawlError::HttpError(format!("Getting batch scrape errors {}", id.as_ref()), e)
            })?;

        self.handle_response(response, "batch scrape errors").await
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    #[tokio::test]
    async fn test_start_batch_scrape_with_mock() {
        let mut server = mockito::Server::new_async().await;

        let mock = server
            .mock("POST", "/v2/batch/scrape")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(
                json!({
                    "success": true,
                    "id": "batch-123",
                    "url": "https://api.firecrawl.dev/v2/batch/scrape/batch-123"
                })
                .to_string(),
            )
            .create();

        let client = Client::new_selfhosted(server.url(), Some("test_key")).unwrap();
        let urls = vec![
            "https://example.com".to_string(),
            "https://example.org".to_string(),
        ];

        let response = client.start_batch_scrape(urls, None).await.unwrap();

        assert!(response.success);
        assert_eq!(response.id, "batch-123");
        mock.assert();
    }

    #[tokio::test]
    async fn test_get_batch_scrape_status_with_mock() {
        let mut server = mockito::Server::new_async().await;

        let mock = server
            .mock("GET", "/v2/batch/scrape/batch-123")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(
                json!({
                    "status": "completed",
                    "total": 3,
                    "completed": 3,
                    "creditsUsed": 3,
                    "data": [
                        {
                            "markdown": "# Page 1",
                            "metadata": { "sourceURL": "https://example.com/1", "statusCode": 200 }
                        },
                        {
                            "markdown": "# Page 2",
                            "metadata": { "sourceURL": "https://example.com/2", "statusCode": 200 }
                        }
                    ]
                })
                .to_string(),
            )
            .create();

        let client = Client::new_selfhosted(server.url(), Some("test_key")).unwrap();
        let status = client.get_batch_scrape_status("batch-123").await.unwrap();

        assert_eq!(status.status, JobStatus::Completed);
        assert_eq!(status.total, 3);
        assert_eq!(status.completed, 3);
        assert_eq!(status.data.len(), 2);
        mock.assert();
    }

    #[tokio::test]
    async fn test_batch_scrape_with_invalid_urls() {
        let mut server = mockito::Server::new_async().await;

        let mock = server
            .mock("POST", "/v2/batch/scrape")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(
                json!({
                    "success": true,
                    "id": "batch-456",
                    "url": "https://api.firecrawl.dev/v2/batch/scrape/batch-456",
                    "invalidURLs": ["not-a-url"]
                })
                .to_string(),
            )
            .create();

        let client = Client::new_selfhosted(server.url(), Some("test_key")).unwrap();
        let urls = vec!["https://example.com".to_string(), "not-a-url".to_string()];

        let options = BatchScrapeOptions {
            ignore_invalid_urls: Some(true),
            ..Default::default()
        };

        let response = client.start_batch_scrape(urls, options).await.unwrap();

        assert!(response.success);
        assert_eq!(response.invalid_urls, Some(vec!["not-a-url".to_string()]));
        mock.assert();
    }

    #[tokio::test]
    async fn test_batch_scrape_sync() {
        let mut server = mockito::Server::new_async().await;

        // Mock the start endpoint
        let start_mock = server
            .mock("POST", "/v2/batch/scrape")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(
                json!({
                    "success": true,
                    "id": "batch-789",
                    "url": "https://api.firecrawl.dev/v2/batch/scrape/batch-789"
                })
                .to_string(),
            )
            .create();

        // Mock the status endpoint (completed immediately)
        let status_mock = server
            .mock("GET", "/v2/batch/scrape/batch-789")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(
                json!({
                    "status": "completed",
                    "total": 2,
                    "completed": 2,
                    "data": [
                        {
                            "markdown": "# Content",
                            "metadata": { "sourceURL": "https://example.com", "statusCode": 200 }
                        }
                    ]
                })
                .to_string(),
            )
            .create();

        let client = Client::new_selfhosted(server.url(), Some("test_key")).unwrap();
        let urls = vec!["https://example.com".to_string()];

        let result = client.batch_scrape(urls, None).await.unwrap();

        assert_eq!(result.status, JobStatus::Completed);
        assert_eq!(result.data.len(), 1);
        start_mock.assert();
        status_mock.assert();
    }

    #[tokio::test]
    async fn test_get_batch_scrape_errors() {
        let mut server = mockito::Server::new_async().await;

        let mock = server
            .mock("GET", "/v2/batch/scrape/batch-123/errors")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(
                json!({
                    "errors": [
                        {
                            "id": "err-1",
                            "url": "https://example.com/broken",
                            "error": "Connection timeout"
                        }
                    ],
                    "robotsBlocked": []
                })
                .to_string(),
            )
            .create();

        let client = Client::new_selfhosted(server.url(), Some("test_key")).unwrap();
        let errors = client.get_batch_scrape_errors("batch-123").await.unwrap();

        assert_eq!(errors.errors.len(), 1);
        assert_eq!(errors.errors[0].error, "Connection timeout");
        mock.assert();
    }
}