firecrawl 2.10.0

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
//! Monitor endpoint for Firecrawl API v2.

use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::client::Client;
use crate::FirecrawlError;

#[derive(Deserialize, Serialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct MonitorSchedule {
    pub cron: String,
    pub timezone: Option<String>,
}

#[serde_with::skip_serializing_none]
#[derive(Deserialize, Serialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct CreateMonitorRequest {
    pub name: String,
    pub schedule: MonitorSchedule,
    pub targets: Vec<Value>,
    pub webhook: Option<Value>,
    pub notification: Option<Value>,
    pub retention_days: Option<u32>,
    /// Optional natural-language description of what the monitor is
    /// watching for (max 2000 chars). When `goal` is set and
    /// `judge_enabled` is left as `None`, the API automatically enables
    /// judging for this monitor.
    pub goal: Option<String>,
    pub judge_enabled: Option<bool>,
}

#[serde_with::skip_serializing_none]
#[derive(Deserialize, Serialize, Debug, Default, Clone)]
#[serde(rename_all = "camelCase")]
pub struct UpdateMonitorRequest {
    pub name: Option<String>,
    pub status: Option<String>,
    pub schedule: Option<MonitorSchedule>,
    pub targets: Option<Vec<Value>>,
    pub webhook: Option<Value>,
    pub notification: Option<Value>,
    pub retention_days: Option<u32>,
    /// Same semantics as on [`CreateMonitorRequest`]; leave as `None` to
    /// keep the existing values.
    pub goal: Option<String>,
    pub judge_enabled: Option<bool>,
}

#[derive(Deserialize, Serialize, Debug, Default, Clone)]
#[serde(rename_all = "camelCase")]
pub struct MonitorSummary {
    pub total_pages: u32,
    pub same: u32,
    pub changed: u32,
    pub new: u32,
    pub removed: u32,
    pub error: u32,
}

#[derive(Deserialize, Serialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct Monitor {
    pub id: String,
    pub name: String,
    pub status: String,
    pub schedule: MonitorSchedule,
    pub next_run_at: Option<String>,
    pub last_run_at: Option<String>,
    pub current_check_id: Option<String>,
    pub targets: Vec<Value>,
    pub webhook: Option<Value>,
    pub notification: Option<Value>,
    pub retention_days: u32,
    pub estimated_credits_per_month: Option<u32>,
    pub last_check_summary: Option<MonitorSummary>,
    pub goal: Option<String>,
    #[serde(default)]
    pub judge_enabled: bool,
    pub created_at: String,
    pub updated_at: String,
}

#[derive(Deserialize, Serialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct MonitorCheck {
    pub id: String,
    pub monitor_id: String,
    pub status: String,
    pub trigger: String,
    pub scheduled_for: Option<String>,
    pub started_at: Option<String>,
    pub finished_at: Option<String>,
    pub estimated_credits: Option<u32>,
    pub reserved_credits: Option<u32>,
    pub actual_credits: Option<u32>,
    pub billing_status: String,
    pub summary: MonitorSummary,
    pub target_results: Option<Value>,
    pub notification_status: Option<Value>,
    pub error: Option<String>,
    pub created_at: String,
    pub updated_at: String,
}

/// Per-field diff entry returned for monitors that requested JSON extraction.
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct MonitorJsonFieldDiff {
    pub previous: Value,
    pub current: Value,
}

/// Diff payload returned alongside a monitor page when its scrape produced
/// a change. The shape depends on what the monitor's formats asked for:
///
/// - markdown-only monitors  → `text` is the unified diff and `json` is
///   the `parseDiff` AST (a `{ "files": [...] }` object).
/// - JSON-extraction monitors → `json` is the per-field
///   `{ previous, current }` map and `text` is absent.
/// - mixed (JSON + git-diff) monitors → both `text` (markdown sidecar)
///   and `json` (field-level diff) are present.
///
/// `json` is kept as a raw [`serde_json::Value`] so callers can decode it
/// into either shape (`HashMap<String, MonitorJsonFieldDiff>` for the
/// field-diff case, or a `{ files: [...] }` struct for the parseDiff AST).
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct MonitorPageDiff {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub text: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub json: Option<Value>,
}

/// Snapshot of the current JSON extraction at this run. Present on JSON
/// and mixed-mode monitors; absent for markdown-only.
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct MonitorPageSnapshot {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub json: Option<Value>,
}

/// Judge's verdict on whether a page change is meaningful. Populated on
/// monitor check pages when the monitor has a `goal` set and judging is
/// enabled.
#[derive(Deserialize, Serialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct MonitorPageJudgment {
    pub meaningful: bool,
    pub confidence: String,
    pub reason: String,
    pub fields: Vec<String>,
}

#[derive(Deserialize, Serialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct MonitorCheckPage {
    pub id: String,
    pub target_id: String,
    pub url: String,
    pub status: String,
    pub previous_scrape_id: Option<String>,
    pub current_scrape_id: Option<String>,
    pub status_code: Option<u16>,
    pub error: Option<String>,
    pub metadata: Option<Value>,
    pub diff: Option<MonitorPageDiff>,
    pub snapshot: Option<MonitorPageSnapshot>,
    pub judgment: Option<MonitorPageJudgment>,
    pub created_at: String,
}

#[derive(Deserialize, Serialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct MonitorCheckDetail {
    #[serde(flatten)]
    pub check: MonitorCheck,
    pub pages: Vec<MonitorCheckPage>,
    pub next: Option<String>,
}

#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
struct DataResponse<T> {
    data: T,
}

#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
struct SuccessResponse {
    success: bool,
}

fn query(limit: Option<u32>, offset: Option<u32>, status: Option<&str>) -> String {
    let mut params = Vec::new();
    if let Some(limit) = limit {
        params.push(format!("limit={}", limit));
    }
    if let Some(offset) = offset {
        params.push(format!("offset={}", offset));
    }
    if let Some(status) = status {
        params.push(format!("status={}", status));
    }
    if params.is_empty() {
        String::new()
    } else {
        format!("?{}", params.join("&"))
    }
}

fn check_page_query(limit: Option<u32>, skip: Option<u32>, status: Option<&str>) -> String {
    let mut params = Vec::new();
    if let Some(limit) = limit {
        params.push(format!("limit={}", limit));
    }
    if let Some(skip) = skip {
        params.push(format!("skip={}", skip));
    }
    if let Some(status) = status {
        params.push(format!("status={}", status));
    }
    if params.is_empty() {
        String::new()
    } else {
        format!("?{}", params.join("&"))
    }
}

impl Client {
    pub async fn create_monitor(
        &self,
        request: CreateMonitorRequest,
    ) -> Result<Monitor, FirecrawlError> {
        let response = self
            .client
            .post(self.url("/monitor"))
            .headers(self.prepare_headers(None))
            .json(&request)
            .send()
            .await
            .map_err(|e| FirecrawlError::HttpError("Creating monitor".to_string(), e))?;

        let response: DataResponse<Monitor> =
            self.handle_response(response, "create monitor").await?;
        Ok(response.data)
    }

    pub async fn list_monitors(
        &self,
        limit: Option<u32>,
        offset: Option<u32>,
    ) -> Result<Vec<Monitor>, FirecrawlError> {
        let response = self
            .client
            .get(self.url(&format!("/monitor{}", query(limit, offset, None))))
            .headers(self.prepare_headers(None))
            .send()
            .await
            .map_err(|e| FirecrawlError::HttpError("Listing monitors".to_string(), e))?;

        let response: DataResponse<Vec<Monitor>> =
            self.handle_response(response, "list monitors").await?;
        Ok(response.data)
    }

    pub async fn get_monitor(
        &self,
        monitor_id: impl AsRef<str>,
    ) -> Result<Monitor, FirecrawlError> {
        let response = self
            .client
            .get(self.url(&format!("/monitor/{}", monitor_id.as_ref())))
            .headers(self.prepare_headers(None))
            .send()
            .await
            .map_err(|e| FirecrawlError::HttpError("Getting monitor".to_string(), e))?;

        let response: DataResponse<Monitor> = self.handle_response(response, "get monitor").await?;
        Ok(response.data)
    }

    pub async fn update_monitor(
        &self,
        monitor_id: impl AsRef<str>,
        request: UpdateMonitorRequest,
    ) -> Result<Monitor, FirecrawlError> {
        let response = self
            .client
            .patch(self.url(&format!("/monitor/{}", monitor_id.as_ref())))
            .headers(self.prepare_headers(None))
            .json(&request)
            .send()
            .await
            .map_err(|e| FirecrawlError::HttpError("Updating monitor".to_string(), e))?;

        let response: DataResponse<Monitor> =
            self.handle_response(response, "update monitor").await?;
        Ok(response.data)
    }

    pub async fn delete_monitor(
        &self,
        monitor_id: impl AsRef<str>,
    ) -> Result<bool, FirecrawlError> {
        let response = self
            .client
            .delete(self.url(&format!("/monitor/{}", monitor_id.as_ref())))
            .headers(self.prepare_headers(None))
            .send()
            .await
            .map_err(|e| FirecrawlError::HttpError("Deleting monitor".to_string(), e))?;

        let response: SuccessResponse = self.handle_response(response, "delete monitor").await?;
        Ok(response.success)
    }

    pub async fn run_monitor(
        &self,
        monitor_id: impl AsRef<str>,
    ) -> Result<MonitorCheck, FirecrawlError> {
        let response = self
            .client
            .post(self.url(&format!("/monitor/{}/run", monitor_id.as_ref())))
            .headers(self.prepare_headers(None))
            .json(&serde_json::json!({}))
            .send()
            .await
            .map_err(|e| FirecrawlError::HttpError("Running monitor".to_string(), e))?;

        let response: DataResponse<MonitorCheck> =
            self.handle_response(response, "run monitor").await?;
        Ok(response.data)
    }

    pub async fn list_monitor_checks(
        &self,
        monitor_id: impl AsRef<str>,
        limit: Option<u32>,
        offset: Option<u32>,
    ) -> Result<Vec<MonitorCheck>, FirecrawlError> {
        let path = format!(
            "/monitor/{}/checks{}",
            monitor_id.as_ref(),
            query(limit, offset, None)
        );
        let response = self
            .client
            .get(self.url(&path))
            .headers(self.prepare_headers(None))
            .send()
            .await
            .map_err(|e| FirecrawlError::HttpError("Listing monitor checks".to_string(), e))?;

        let response: DataResponse<Vec<MonitorCheck>> = self
            .handle_response(response, "list monitor checks")
            .await?;
        Ok(response.data)
    }

    pub async fn get_monitor_check(
        &self,
        monitor_id: impl AsRef<str>,
        check_id: impl AsRef<str>,
        limit: Option<u32>,
        skip: Option<u32>,
        status: Option<&str>,
    ) -> Result<MonitorCheckDetail, FirecrawlError> {
        let path = format!(
            "/monitor/{}/checks/{}{}",
            monitor_id.as_ref(),
            check_id.as_ref(),
            check_page_query(limit, skip, status)
        );
        let response = self
            .client
            .get(self.url(&path))
            .headers(self.prepare_headers(None))
            .send()
            .await
            .map_err(|e| FirecrawlError::HttpError("Getting monitor check".to_string(), e))?;

        let response: DataResponse<MonitorCheckDetail> =
            self.handle_response(response, "get monitor check").await?;
        let mut check = response.data;

        while let Some(next) = check.next.clone() {
            let response = self
                .client
                .get(next)
                .headers(self.prepare_headers(None))
                .send()
                .await
                .map_err(|e| {
                    FirecrawlError::HttpError("Getting monitor check page".to_string(), e)
                })?;
            let response: DataResponse<MonitorCheckDetail> = self
                .handle_response(response, "get monitor check page")
                .await?;
            check.pages.extend(response.data.pages);
            check.next = response.data.next;
        }

        Ok(check)
    }

    pub async fn get_monitor_check_page(
        &self,
        monitor_id: impl AsRef<str>,
        check_id: impl AsRef<str>,
        limit: Option<u32>,
        skip: Option<u32>,
        status: Option<&str>,
    ) -> Result<MonitorCheckDetail, FirecrawlError> {
        let path = format!(
            "/monitor/{}/checks/{}{}",
            monitor_id.as_ref(),
            check_id.as_ref(),
            check_page_query(limit, skip, status)
        );
        let response = self
            .client
            .get(self.url(&path))
            .headers(self.prepare_headers(None))
            .send()
            .await
            .map_err(|e| FirecrawlError::HttpError("Getting monitor check".to_string(), e))?;

        let response: DataResponse<MonitorCheckDetail> =
            self.handle_response(response, "get monitor check").await?;
        Ok(response.data)
    }
}