Spaces:
Sleeping
Sleeping
File size: 10,091 Bytes
097eaf0 | 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 | //! Map endpoint for Firecrawl API v2.
use serde::{Deserialize, Serialize};
use crate::client::Client;
use crate::types::{LocationConfig, SearchResultWeb, SitemapMode};
use crate::FirecrawlError;
/// Options for mapping a URL.
#[serde_with::skip_serializing_none]
#[derive(Deserialize, Serialize, Debug, Default, Clone)]
#[serde(rename_all = "camelCase")]
pub struct MapOptions {
/// Search query to filter discovered links.
pub search: Option<String>,
/// How to handle the sitemap.
pub sitemap: Option<SitemapMode>,
/// Include subdomains in the mapping.
pub include_subdomains: Option<bool>,
/// Ignore query parameters when deduplicating URLs.
pub ignore_query_parameters: Option<bool>,
/// Maximum number of links to return.
pub limit: Option<u32>,
/// Timeout in milliseconds.
pub timeout: Option<u32>,
/// Integration identifier for tracking.
pub integration: Option<String>,
/// Location configuration for proxy routing.
pub location: Option<LocationConfig>,
}
/// Request body for map endpoint.
#[derive(Deserialize, Serialize, Debug, Default)]
#[serde(rename_all = "camelCase")]
struct MapRequest {
url: String,
#[serde(flatten)]
options: MapOptions,
}
/// Response from map endpoint.
#[derive(Deserialize, Serialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct MapResponse {
/// Whether the request was successful.
pub success: bool,
/// Discovered links with metadata.
pub links: Vec<SearchResultWeb>,
/// Warning message if any.
pub warning: Option<String>,
}
impl Client {
/// Maps a URL to discover all associated links.
///
/// This endpoint discovers links from a website's sitemap, page content,
/// and other sources without fully scraping each page.
///
/// # Arguments
///
/// * `url` - The URL to map.
/// * `options` - Optional mapping configuration.
///
/// # Returns
///
/// A `MapResponse` containing the discovered links.
///
/// # Example
///
/// ```no_run
/// use firecrawl::{Client, MapOptions, SitemapMode};
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = Client::new("your-api-key")?;
///
/// // Simple map
/// let response = client.map("https://example.com", None).await?;
/// println!("Found {} links", response.links.len());
///
/// // Map with options
/// let options = MapOptions {
/// sitemap: Some(SitemapMode::Include),
/// include_subdomains: Some(true),
/// limit: Some(1000),
/// ..Default::default()
/// };
/// let response = client.map("https://example.com", options).await?;
///
/// for link in response.links {
/// println!("URL: {}, Title: {:?}", link.url, link.title);
/// }
///
/// Ok(())
/// }
/// ```
pub async fn map(
&self,
url: impl AsRef<str>,
options: impl Into<Option<MapOptions>>,
) -> Result<MapResponse, FirecrawlError> {
let body = MapRequest {
url: url.as_ref().to_string(),
options: options.into().unwrap_or_default(),
};
let headers = self.prepare_headers(None);
let response = self
.client
.post(self.url("/map"))
.headers(headers)
.json(&body)
.send()
.await
.map_err(|e| FirecrawlError::HttpError(format!("Mapping {:?}", url.as_ref()), e))?;
self.handle_response(response, "map").await
}
/// Maps a URL and returns just the list of URLs.
///
/// This is a convenience method that returns only the URL strings.
///
/// # Arguments
///
/// * `url` - The URL to map.
/// * `options` - Optional mapping configuration.
///
/// # Returns
///
/// A vector of discovered URL strings.
///
/// # 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 urls = client.map_urls("https://example.com", None).await?;
/// for url in urls {
/// println!("{}", url);
/// }
///
/// Ok(())
/// }
/// ```
pub async fn map_urls(
&self,
url: impl AsRef<str>,
options: impl Into<Option<MapOptions>>,
) -> Result<Vec<String>, FirecrawlError> {
let response = self.map(url, options).await?;
Ok(response.links.into_iter().map(|link| link.url).collect())
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[tokio::test]
async fn test_map_with_mock() {
let mut server = mockito::Server::new_async().await;
let mock = server
.mock("POST", "/v2/map")
.with_status(200)
.with_header("content-type", "application/json")
.with_body(
json!({
"success": true,
"links": [
{
"url": "https://example.com/",
"title": "Example Domain",
"description": "Home page"
},
{
"url": "https://example.com/about",
"title": "About Us"
},
{
"url": "https://example.com/contact"
}
]
})
.to_string(),
)
.create();
let client = Client::new_selfhosted(server.url(), Some("test_key")).unwrap();
let response = client.map("https://example.com", None).await.unwrap();
assert!(response.success);
assert_eq!(response.links.len(), 3);
assert_eq!(response.links[0].url, "https://example.com/");
assert_eq!(response.links[0].title, Some("Example Domain".to_string()));
mock.assert();
}
#[tokio::test]
async fn test_map_with_options() {
let mut server = mockito::Server::new_async().await;
let mock = server
.mock("POST", "/v2/map")
.with_status(200)
.with_header("content-type", "application/json")
.with_body(
json!({
"success": true,
"links": [
{ "url": "https://example.com/page1" },
{ "url": "https://example.com/page2" }
]
})
.to_string(),
)
.create();
let client = Client::new_selfhosted(server.url(), Some("test_key")).unwrap();
let options = MapOptions {
sitemap: Some(SitemapMode::Include),
include_subdomains: Some(true),
limit: Some(100),
..Default::default()
};
let response = client.map("https://example.com", options).await.unwrap();
assert!(response.success);
assert_eq!(response.links.len(), 2);
mock.assert();
}
#[tokio::test]
async fn test_map_urls() {
let mut server = mockito::Server::new_async().await;
let mock = server
.mock("POST", "/v2/map")
.with_status(200)
.with_header("content-type", "application/json")
.with_body(
json!({
"success": true,
"links": [
{ "url": "https://example.com/page1" },
{ "url": "https://example.com/page2" },
{ "url": "https://example.com/page3" }
]
})
.to_string(),
)
.create();
let client = Client::new_selfhosted(server.url(), Some("test_key")).unwrap();
let urls = client.map_urls("https://example.com", None).await.unwrap();
assert_eq!(urls.len(), 3);
assert_eq!(urls[0], "https://example.com/page1");
mock.assert();
}
#[tokio::test]
async fn test_map_with_search_filter() {
let mut server = mockito::Server::new_async().await;
let mock = server
.mock("POST", "/v2/map")
.with_status(200)
.with_header("content-type", "application/json")
.with_body(
json!({
"success": true,
"links": [
{ "url": "https://example.com/blog/post1" },
{ "url": "https://example.com/blog/post2" }
]
})
.to_string(),
)
.create();
let client = Client::new_selfhosted(server.url(), Some("test_key")).unwrap();
let options = MapOptions {
search: Some("blog".to_string()),
..Default::default()
};
let response = client.map("https://example.com", options).await.unwrap();
assert!(response.success);
assert_eq!(response.links.len(), 2);
mock.assert();
}
#[tokio::test]
async fn test_map_error_response() {
let mut server = mockito::Server::new_async().await;
let mock = server
.mock("POST", "/v2/map")
.with_status(400)
.with_header("content-type", "application/json")
.with_body(
json!({
"success": false,
"error": "Invalid URL"
})
.to_string(),
)
.create();
let client = Client::new_selfhosted(server.url(), Some("test_key")).unwrap();
let result = client.map("invalid-url", None).await;
assert!(result.is_err());
mock.assert();
}
}
|