> ## Documentation Index
> Fetch the complete documentation index at: https://docs.firecrawl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Rust

> Firecrawl Rust SDK は、Web サイトを簡単に Markdown に変換できる Firecrawl API のラッパーです。

<div id="installation">
  ## インストール
</div>

公式の Rust SDK は、Firecrawl のモノレポ内にある [apps/rust-sdk](https://github.com/firecrawl/firecrawl/tree/main/apps/rust-sdk) で管理されています。

Firecrawl Rust SDK をインストールするには、[crates.io](https://crates.io/crates/firecrawl) から依存関係を追加します。

```toml theme={null}
[dependencies]
firecrawl = "2"
tokio = { version = "1", features = ["full"] }
serde_json = "1"
```

または Cargo でインストールします。

```bash theme={null}
cargo add firecrawl
cargo add tokio --features full
cargo add serde_json
```

<Note>Rust 1.70以降が必要です。</Note>

<div id="usage">
  ## 使用方法
</div>

1. [firecrawl.dev](https://firecrawl.dev) でAPIキーを取得します
2. APIキーを `FIRECRAWL_API_KEY` という名前の環境変数に設定するか、`Client::new(...)` に直接渡します

ページをスクレイピングし、そのMarkdownを出力します:

```rust theme={null}
use firecrawl::{Client, ScrapeOptions, Format};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Client::new("fc-YOUR-API-KEY")?;

    let doc = client.scrape(
        "https://firecrawl.dev",
        ScrapeOptions {
            formats: Some(vec![Format::Markdown]),
            ..Default::default()
        },
    ).await?;

    println!("{}", doc.markdown.unwrap_or_default());
    Ok(())
}
```

以下のセクションでは、クロール、マッピング、検索、その他のSDKメソッドについて説明します。

<div id="scraping-a-url">
  ### URLのスクレイピング
</div>

単一のURLをスクレイピングするには、`scrape`メソッドを使用します。

```rust theme={null}
use firecrawl::{Client, ScrapeOptions, Format};

let doc = client.scrape(
    "https://firecrawl.dev",
    ScrapeOptions {
        formats: Some(vec![Format::Markdown, Format::Html]),
        only_main_content: Some(true),
        wait_for: Some(5000),
        ..Default::default()
    },
).await?;

println!("{}", doc.markdown.unwrap_or_default());
if let Some(meta) = &doc.metadata {
    println!("{:?}", meta.title);
}
```

<div id="json-extraction">
  #### JSON抽出
</div>

`scrape_with_schema` を使用して、構造化されたJSONを抽出します:

```rust theme={null}
use firecrawl::Client;
use serde_json::json;

let schema = json!({
    "type": "object",
    "properties": {
        "name": { "type": "string" },
        "price": { "type": "number" }
    }
});

let data = client.scrape_with_schema(
    "https://example.com/product",
    schema,
    Some("Extract the product name and price"),
).await?;

println!("{}", serde_json::to_string_pretty(&data)?);
```

または、`ScrapeOptions` で直接 JSON 抽出を設定することもできます:

```rust theme={null}
use firecrawl::{Client, ScrapeOptions, Format, JsonOptions};
use serde_json::json;

let doc = client.scrape(
    "https://example.com/product",
    ScrapeOptions {
        formats: Some(vec![Format::Json]),
        json_options: Some(JsonOptions {
            schema: Some(json!({
                "type": "object",
                "properties": {
                    "name": { "type": "string" },
                    "price": { "type": "number" }
                }
            })),
            prompt: Some("Extract the product name and price".to_string()),
            ..Default::default()
        }),
        ..Default::default()
    },
).await?;

println!("{:?}", doc.json);
```

<div id="parsing-uploaded-files">
  ### アップロードしたファイルの解析
</div>

`parse` を使うと、ローカルファイル (`.html`、`.htm`、`.pdf`、`.docx`、`.doc`、`.odt`、`.rtf`、`.xlsx`、`.xls`) を multipart form data として `/v2/parse` にアップロードできます。この endpoint は、指定したフォーマットを含む `Document` を返します。

`ParseOptions` では、`/v2/parse` が受け付けないスクレイピング専用のフィールド (`actions`、`waitFor`、`location`、`mobile`、`screenshot`、`branding`、`changeTracking` など) を意図的に除外しています。

メモリ上のバイト列、またはパスから直接 `ParseFile` を作成します。

```rust theme={null}
use firecrawl::{Client, ParseFile, ParseFormat, ParseOptions};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Client::new("fc-YOUR-API-KEY")?;

    let file = ParseFile::from_bytes(
        "upload.html",
        b"<!DOCTYPE html><html><body><h1>Rust Parse</h1></body></html>".to_vec(),
    )
    .with_content_type("text/html");

    let options = ParseOptions {
        formats: Some(vec![ParseFormat::Markdown, ParseFormat::Html]),
        only_main_content: Some(true),
        ..Default::default()
    };

    let doc = client.parse(file, Some(options)).await?;
    println!("{}", doc.markdown.unwrap_or_default());
    Ok(())
}
```

または、ディスクからファイルを読み込み、オプションは省略します:

```rust theme={null}
use firecrawl::{Client, ParseFile};

let client = Client::new("fc-YOUR-API-KEY")?;
let file = ParseFile::from_path("./report.pdf")?;

let doc = client.parse(file, None).await?;
println!("{}", doc.markdown.unwrap_or_default());
```

<div id="parsefile">
  #### `ParseFile`
</div>

| Constructor                              | 説明                                                  |
| ---------------------------------------- | --------------------------------------------------- |
| `ParseFile::from_bytes(filename, bytes)` | ファイル名とメモリ上のバイト列から生成                                 |
| `ParseFile::from_path(path)`             | ディスクからバイト列を読み込み、ファイル名を取得                            |
| `.with_content_type(content_type)`       | MIME タイプのヒントを付与 (例: `text/html`, `application/pdf`) |

<div id="parseoptions">
  #### `ParseOptions`
</div>

利用可能なフィールド (すべて任意、ワイヤ形式では camelCase) :

* `formats: Vec<ParseFormat>` — `Markdown`、`Html`、`RawHtml`、`Links`、`Images`、`Summary`、`Json`、`Attributes` のいずれか
* `only_main_content: bool`
* `include_tags: Vec<String>` / `exclude_tags: Vec<String>`
* `headers: HashMap<String, String>`
* `timeout: u32` (ms)
* `parsers: Vec<ParserConfig>` (例: PDF パーサーの設定)
* `skip_tls_verification: bool`
* `remove_base64_images: bool`
* `fast_mode: bool`
* `block_ads: bool`
* `proxy: ParseProxyType` (`Basic` または `Auto`)
* `json_options: JsonOptions`
* `attribute_selectors: Vec<AttributeSelector>`
* `zero_data_retention: bool`
* `integration: String`, `origin: String`, `use_mock: String`

<div id="crawling-a-website">
  ### Web サイトのクロール
</div>

Web サイトをクロールして完了を待つには、`crawl` を使用します。

```rust theme={null}
use firecrawl::{Client, CrawlOptions, ScrapeOptions, Format};

let job = client.crawl(
    "https://firecrawl.dev",
    CrawlOptions {
        limit: Some(50),
        max_discovery_depth: Some(3),
        scrape_options: Some(ScrapeOptions {
            formats: Some(vec![Format::Markdown]),
            ..Default::default()
        }),
        ..Default::default()
    },
).await?;

println!("Status: {:?}", job.status);
println!("Progress: {}/{}", job.completed, job.total);

for page in &job.data {
    if let Some(meta) = &page.metadata {
        println!("{:?}", meta.source_url);
    }
}
```

<div id="start-a-crawl">
  ### クロールを開始する
</div>

`start_crawl` を使うと、待たずにジョブを開始できます。

```rust theme={null}
use firecrawl::{Client, CrawlOptions};

let start = client.start_crawl(
    "https://firecrawl.dev",
    CrawlOptions {
        limit: Some(100),
        ..Default::default()
    },
).await?;

println!("Job ID: {}", start.id);
```

<div id="checking-crawl-status">
  ### クロールのステータスを確認
</div>

`get_crawl_status`でクロールの進行状況を確認できます。

```rust theme={null}
let status = client.get_crawl_status(&start.id).await?;
println!("Status: {:?}", status.status);
println!("Progress: {}/{}", status.completed, status.total);
```

<div id="cancelling-a-crawl">
  ### クロールをキャンセルする
</div>

実行中のクロールは `cancel_crawl` でキャンセルできます。

```rust theme={null}
let result = client.cancel_crawl(&start.id).await?;
println!("{:?}", result);
```

<div id="checking-crawl-errors">
  ### クロールエラーの確認
</div>

`get_crawl_errors` でクロールジョブのエラーを取得します。

```rust theme={null}
let errors = client.get_crawl_errors(&start.id).await?;
println!("{:?}", errors);
```

<div id="mapping-a-website">
  ### Web サイトをマッピングする
</div>

`map` を使用して Web サイト内のリンクを見つけます。

```rust theme={null}
use firecrawl::{Client, MapOptions};

let response = client.map(
    "https://firecrawl.dev",
    MapOptions {
        limit: Some(100),
        search: Some("blog".to_string()),
        ..Default::default()
    },
).await?;

for link in &response.links {
    println!("{} - {}", link.url, link.title.as_deref().unwrap_or(""));
}
```

URL のみのシンプルな結果を得るには、`map_urls` を使用します:

```rust theme={null}
let urls = client.map_urls("https://firecrawl.dev", None).await?;
for url in &urls {
    println!("{}", url);
}
```

<div id="searching-the-web">
  ### Webを検索する
</div>

`search` を使うと、任意の設定で検索できます。

```rust theme={null}
use firecrawl::{Client, SearchOptions};

let results = client.search(
    "firecrawl web scraping",
    SearchOptions {
        limit: Some(10),
        ..Default::default()
    },
).await?;

if let Some(web) = results.data.web {
    for item in web {
        match item {
            firecrawl::SearchResultOrDocument::WebResult(r) => {
                println!("{} - {}", r.url, r.title.unwrap_or_default());
            }
            firecrawl::SearchResultOrDocument::Document(d) => {
                println!("{}", d.markdown.unwrap_or_default());
            }
        }
    }
}
```

スクレイピング済みのドキュメントを直接返す便利なメソッドを使う場合:

```rust theme={null}
let docs = client.search_and_scrape("firecrawl web scraping", 5).await?;
for doc in &docs {
    println!("{}", doc.markdown.as_deref().unwrap_or(""));
}
```

<div id="batch-scraping">
  ### バッチスクレイピング
</div>

`batch_scrape` を使用して、複数のURLを並列でスクレイピングします。

```rust theme={null}
use firecrawl::{Client, BatchScrapeOptions, ScrapeOptions, Format};

let urls = vec![
    "https://firecrawl.dev".to_string(),
    "https://firecrawl.dev/blog".to_string(),
];

let job = client.batch_scrape(
    urls,
    BatchScrapeOptions {
        options: Some(ScrapeOptions {
            formats: Some(vec![Format::Markdown]),
            ..Default::default()
        }),
        ..Default::default()
    },
).await?;

for doc in &job.data {
    println!("{}", doc.markdown.as_deref().unwrap_or(""));
}
```

<div id="agent">
  ### Agent
</div>

`agent` を使って AI エージェントを実行します。

```rust theme={null}
use firecrawl::{Client, AgentOptions};

let result = client.agent(
    AgentOptions {
        prompt: "Find the pricing plans for Firecrawl and compare them".to_string(),
        ..Default::default()
    },
).await?;

println!("{:?}", result.data);
```

構造化された出力用のJSON schema:

```rust theme={null}
use firecrawl::{Client, AgentOptions, AgentModel};
use serde::Deserialize;
use serde_json::json;

#[derive(Debug, Deserialize)]
struct PricingPlan {
    name: String,
    price: String,
}

#[derive(Debug, Deserialize)]
struct PricingData {
    plans: Vec<PricingPlan>,
}

let schema = json!({
    "type": "object",
    "properties": {
        "plans": {
            "type": "array",
            "items": {
                "type": "object",
                "properties": {
                    "name": { "type": "string" },
                    "price": { "type": "string" }
                }
            }
        }
    }
});

let result: Option<PricingData> = client.agent_with_schema(
    vec!["https://firecrawl.dev".to_string()],
    "Extract pricing plan details",
    schema,
).await?;

if let Some(data) = result {
    for plan in &data.plans {
        println!("{}: {}", plan.name, plan.price);
    }
}
```

<div id="scrape-bound-interactive-session">
  ## スクレイピングに紐づいたインタラクティブセッション
</div>

スクレイピングジョブIDを使用して、同じコンテキストで後続のブラウザコードを実行できます。

* `interact(...)` は、スクレイピングに紐づいたブラウザセッション内でコードまたはプロンプトを実行します。
* `stop_interaction(...)` は、作業完了後にインタラクティブセッションを停止します。

```rust theme={null}
use firecrawl::{Client, ScrapeExecuteOptions, ScrapeExecuteLanguage};

let scrape_job_id = "550e8400-e29b-41d4-a716-446655440000";

// ブラウザセッションでコードを実行する
let run = client.interact(
    scrape_job_id,
    ScrapeExecuteOptions {
        code: Some("console.log(await page.title())".to_string()),
        language: Some(ScrapeExecuteLanguage::Node),
        timeout: Some(60),
        ..Default::default()
    },
).await?;

println!("{:?}", run.stdout);

// または自然言語プロンプトを使用する
let run = client.interact(
    scrape_job_id,
    ScrapeExecuteOptions {
        prompt: Some("Click the pricing tab and summarize the plans".to_string()),
        ..Default::default()
    },
).await?;

// 完了したらセッションを停止する
client.stop_interaction(scrape_job_id).await?;
```

<div id="configuration">
  ## 設定
</div>

`Client::new(...)` と `Client::new_selfhosted(...)` でクライアントを作成します。

| Option                                     | Description                                                      |
| ------------------------------------------ | ---------------------------------------------------------------- |
| `Client::new(api_key)`                     | Firecrawl のクラウドサービス (`https://api.firecrawl.dev`) 用のクライアントを作成します |
| `Client::new_selfhosted(api_url, api_key)` | セルフホストの Firecrawl インスタンス用のクライアントを作成します                           |

```rust theme={null}
use firecrawl::Client;

// クラウドサービス
let client = Client::new("fc-your-api-key")?;

// セルフホスト
let client = Client::new_selfhosted(
    "http://localhost:3002",
    Some("fc-your-api-key"),
)?;

// 認証なしのセルフホスト
let client = Client::new_selfhosted(
    "http://localhost:3002",
    None::<&str>,
)?;
```

<div id="environment-variable">
  ### 環境変数
</div>

キーを直接渡す代わりに、`FIRECRAWL_API_KEY` 環境変数を設定してください。

```bash theme={null}
export FIRECRAWL_API_KEY=fc-YOUR-API-KEY
```

```rust theme={null}
let api_key = std::env::var("FIRECRAWL_API_KEY")
    .expect("FIRECRAWL_API_KEY must be set");
let client = Client::new(api_key)?;
```

<div id="poll-intervals">
  ### ポーリング間隔
</div>

同期メソッド (`crawl`、`batch_scrape`、`agent`) は、完了するまでポーリングを続けます。ポーリング間隔は、`options` 構造体でカスタマイズできます。

```rust theme={null}
use firecrawl::CrawlOptions;

let options = CrawlOptions {
    limit: Some(50),
    poll_interval: Some(3000), // 3秒ごとにポーリング（デフォルト: 2000ms）
    ..Default::default()
};
```

<div id="error-handling">
  ## エラー処理
</div>

この SDK は、`Error`、`Debug`、`Display` を実装する `FirecrawlError` 列挙型を使用します。すべてのメソッドは `Result<T, FirecrawlError>` を返します。

```rust theme={null}
use firecrawl::{Client, FirecrawlError};

match client.scrape("https://example.com", None).await {
    Ok(doc) => println!("{}", doc.markdown.unwrap_or_default()),
    Err(FirecrawlError::HttpRequestFailed(action, status, msg)) => {
        eprintln!("HTTP {}: {} ({})", status, msg, action);
    }
    Err(FirecrawlError::APIError(action, api_err)) => {
        eprintln!("API error ({}): {}", action, api_err.error);
    }
    Err(FirecrawlError::JobFailed(msg)) => {
        eprintln!("Job failed: {}", msg);
    }
    Err(FirecrawlError::Misuse(msg)) => {
        eprintln!("SDK misuse: {}", msg);
    }
    Err(e) => eprintln!("Error: {}", e),
}
```

> Firecrawl API キーを必要とする AI エージェントですか？自動オンボーディング手順については、[firecrawl.dev/agent-onboarding/SKILL.md](https://www.firecrawl.dev/agent-onboarding/SKILL.md) を参照してください。
