快速开始(3/3)
Get started with Firecrawl in .NET. Scrape, search, and interact with web data using the REST API.
Prerequisites
- .NET 6.0+
- A Firecrawl API key — get one free
Search the web
Firecrawl works with .NET through the REST API using HttpClient.
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
var apiKey = Environment.GetEnvironmentVariable("FIRECRAWL_API_KEY");
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
var content = new StringContent(
JsonSerializer.Serialize(new { query = "firecrawl web scraping", limit = 5 }),
Encoding.UTF8,
"application/json"
);
var response = await client.PostAsync("https://api.firecrawl.dev/v2/search", content);
var json = await response.Content.ReadAsStringAsync();
Console.WriteLine(json);
{
"success": true,
"data": {
"web": [
{
"url": "https://docs.firecrawl.dev",
"title": "Firecrawl Documentation",
"markdown": "# Firecrawl\n\nFirecrawl is a web scraping API..."
}
]
}
}
Scrape a page
var scrapeContent = new StringContent(
JsonSerializer.Serialize(new { url = "https://example.com" }),
Encoding.UTF8,
"application/json"
);
var scrapeResponse = await client.PostAsync("https://api.firecrawl.dev/v2/scrape", scrapeContent);
var scrapeJson = await scrapeResponse.Content.ReadAsStringAsync();
using var doc = JsonDocument.Parse(scrapeJson);
var markdown = doc.RootElement.GetProperty("data").GetProperty("markdown").GetString();
Console.WriteLine(markdown);
{
"success": true,
"data": {
"markdown": "# Example Domain\n\nThis domain is for use in illustrative examples...",
"metadata": {
"title": "Example Domain",
"sourceURL": "https://example.com"
}
}
}
Interact with a page
Start a browser session, interact with the page using natural-language prompts, then close the session.
Step 1 — Scrape to start a session
var sessionContent = new StringContent(
JsonSerializer.Serialize(new { url = "https://www.amazon.com", formats = new[] { "markdown" } }),
Encoding.UTF8,
"application/json"
);
var sessionResponse = await client.PostAsync("https://api.firecrawl.dev/v2/scrape", sessionContent);
var sessionJson = await sessionResponse.Content.ReadAsStringAsync();
using var sessionDoc = JsonDocument.Parse(sessionJson);
var scrapeId = sessionDoc.RootElement
.GetProperty("data")
.GetProperty("metadata")
.GetProperty("scrapeId")
.GetString();
Console.WriteLine($"scrapeId: {scrapeId}");
Step 2 — Send interactions
var interactUrl = $"https://api.firecrawl.dev/v2/scrape/{scrapeId}/interact";
// Search for a product
var searchBody = new StringContent(
JsonSerializer.Serialize(new { prompt = "Search for iPhone 16 Pro Max" }),
Encoding.UTF8,
"application/json"
);
var searchResult = await client.PostAsync(interactUrl, searchBody);
Console.WriteLine(await searchResult.Content.ReadAsStringAsync());
// Click on the first result
var clickBody = new StringContent(
JsonSerializer.Serialize(new { prompt = "Click on the first result and tell me the price" }),
Encoding.UTF8,
"application/json"
);
var clickResult = await client.PostAsync(interactUrl, clickBody);
Console.WriteLine(await clickResult.Content.ReadAsStringAsync());
Step 3 — Stop the session
await client.DeleteAsync(interactUrl);
Console.WriteLine("Session stopped");
Reusable client class
For repeated use, wrap the API in a typed client:
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
public class FirecrawlClient
{
private readonly HttpClient _http;
private const string BaseUrl = "https://api.firecrawl.dev/v2";
public FirecrawlClient(string apiKey)
{
_http = new HttpClient();
_http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
}
private async Task<JsonDocument> PostAsync(string endpoint, object payload)
{
var content = new StringContent(
JsonSerializer.Serialize(payload),
Encoding.UTF8,
"application/json"
);
var response = await _http.PostAsync($"{BaseUrl}{endpoint}", content);
response.EnsureSuccessStatusCode();
var json = await response.Content.ReadAsStringAsync();
return JsonDocument.Parse(json);
}
public async Task<JsonDocument> ScrapeAsync(string url)
{
return await PostAsync("/scrape", new { url });
}
public async Task<JsonDocument> SearchAsync(string query, int limit = 5)
{
return await PostAsync("/search", new { query, limit });
}
}
// Usage
var firecrawl = new FirecrawlClient(Environment.GetEnvironmentVariable("FIRECRAWL_API_KEY")!);
var result = await firecrawl.SearchAsync("firecrawl web scraping");
Console.WriteLine(result.RootElement);
Next steps
Search the web and get full page content
All scrape options including formats, actions, and proxies
Click, fill forms, and extract dynamic content
Complete REST API documentation
Use Firecrawl with ASP.NET Core to search, scrape, and interact with web data using the REST API.
Prerequisites
- .NET 6.0+
- A Firecrawl API key — get one free
Configuration
Add your API key to appsettings.json:
{
"Firecrawl": {
"ApiKey": "fc-YOUR-API-KEY",
"BaseUrl": "https://api.firecrawl.dev/v2"
}
}
Or use environment variables / user secrets:
export Firecrawl__ApiKey=fc-YOUR-API-KEY
Create a service
Create Services/FirecrawlService.cs:
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
public class FirecrawlService
{
private readonly HttpClient _http;
private readonly string _baseUrl;
public FirecrawlService(IConfiguration config)
{
_baseUrl = config["Firecrawl:BaseUrl"] ?? "https://api.firecrawl.dev/v2";
_http = new HttpClient();
_http.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", config["Firecrawl:ApiKey"]);
}
public async Task<JsonDocument> SearchAsync(string query, int limit = 5)
{
var content = new StringContent(
JsonSerializer.Serialize(new { query, limit }),
Encoding.UTF8, "application/json");
var response = await _http.PostAsync($"{_baseUrl}/search", content);
response.EnsureSuccessStatusCode();
return JsonDocument.Parse(await response.Content.ReadAsStringAsync());
}
public async Task<JsonDocument> ScrapeAsync(string url)
{
var content = new StringContent(
JsonSerializer.Serialize(new { url }),
Encoding.UTF8, "application/json");
var response = await _http.PostAsync($"{_baseUrl}/scrape", content);
response.EnsureSuccessStatusCode();
return JsonDocument.Parse(await response.Content.ReadAsStringAsync());
}
public async Task<JsonDocument> InteractAsync(string url, string prompt, string? followUp = null)
{
// 1. Scrape to open a browser session
var scrapeContent = new StringContent(
JsonSerializer.Serialize(new { url, formats = new[] { "markdown" } }),
Encoding.UTF8, "application/json");
var scrapeRes = await _http.PostAsync($"{_baseUrl}/scrape", scrapeContent);
scrapeRes.EnsureSuccessStatusCode();
var scrapeDoc = JsonDocument.Parse(await scrapeRes.Content.ReadAsStringAsync());
var scrapeId = scrapeDoc.RootElement
.GetProperty("data").GetProperty("metadata").GetProperty("scrapeId").GetString();
// 2. Send first prompt
var firstPrompt = new StringContent(
JsonSerializer.Serialize(new { prompt }),
Encoding.UTF8, "application/json");
await _http.PostAsync($"{_baseUrl}/scrape/{scrapeId}/interact", firstPrompt);
// 3. Send follow-up prompt
JsonDocument? result = null;
if (followUp != null)
{
var followUpContent = new StringContent(
JsonSerializer.Serialize(new { prompt = followUp }),
Encoding.UTF8, "application/json");
var followUpRes = await _http.PostAsync(
$"{_baseUrl}/scrape/{scrapeId}/interact", followUpContent);
followUpRes.EnsureSuccessStatusCode();
result = JsonDocument.Parse(await followUpRes.Content.ReadAsStringAsync());
}
// 4. Close the session
await _http.DeleteAsync($"{_baseUrl}/scrape/{scrapeId}/interact");
return result ?? scrapeDoc;
}
}
Register and use
In Program.cs:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<FirecrawlService>();
var app = builder.Build();
app.MapPost("/api/search", async (FirecrawlService firecrawl, SearchRequest req) =>
{
var result = await firecrawl.SearchAsync(req.Query, req.Limit);
return Results.Ok(result.RootElement);
});
app.MapPost("/api/scrape", async (FirecrawlService firecrawl, ScrapeRequest req) =>
{
var result = await firecrawl.ScrapeAsync(req.Url);
return Results.Ok(result.RootElement);
});
app.MapPost("/api/interact", async (FirecrawlService firecrawl, InteractRequest req) =>
{
var result = await firecrawl.InteractAsync(req.Url, req.Prompt, req.FollowUp);
return Results.Ok(result.RootElement);
});
app.Run();
record SearchRequest(string Query, int Limit = 5);
record ScrapeRequest(string Url);
record InteractRequest(string Url, string Prompt, string? FollowUp = null);
Run it
dotnet run
Test it
# Search the web
curl -X POST http://localhost:5000/api/search \
-H "Content-Type: application/json" \
-d '{"query": "firecrawl web scraping"}'
# Scrape a page
curl -X POST http://localhost:5000/api/scrape \
-H "Content-Type: application/json" \
-d '{"url": "https://example.com"}'
# Interact with a page
curl -X POST http://localhost:5000/api/interact \
-H "Content-Type: application/json" \
-d '{"url": "https://www.amazon.com", "prompt": "Search for iPhone 16 Pro Max", "followUp": "Click on the first result and tell me the price"}'
Next steps
Search the web and get full page content
All scrape options including formats, actions, and proxies
Click, fill forms, and extract dynamic content
Complete REST API documentation
Install Firecrawl from the Vercel Marketplace, attach it to a project, and use the injected FIRECRAWL_API_KEY in your Vercel app.
Firecrawl is available as a native Vercel Marketplace integration. Installing it provisions Firecrawl for your Vercel project and adds FIRECRAWL_API_KEY to the project's environment variables automatically.
Use this guide when you want Firecrawl billing, API key setup, and project configuration to happen through Vercel.
What the integration does
When you install Firecrawl from the Vercel Marketplace, Vercel connects Firecrawl to a selected project and makes the API key available as an environment variable.
- Provisions a Firecrawl account and API key through the Marketplace flow
- Adds
FIRECRAWL_API_KEYto your Vercel project environment - Keeps Firecrawl billing on your Vercel invoice
- Lets you open Firecrawl from Vercel after the integration is connected
If you already have a Firecrawl API key and want to configure Vercel manually, use the Vercel Functions quickstart instead.
Install from Vercel
- Open the Firecrawl listing on the Vercel Marketplace.
- Click Connect Account.
- Choose the Firecrawl plan you want to use.
- Select the Vercel project that should receive the environment variable.
- Finish the installation flow.
After installation, redeploy your project so Vercel Functions and framework server code can read the new environment variable.
Install the SDK
In your Vercel project, install the Firecrawl Node SDK:
npm install firecrawl
You do not need to paste an API key into your code. Read process.env.FIRECRAWL_API_KEY server-side.
Scrape a page
Create a route handler at app/api/scrape/route.ts:
import { NextResponse } from "next/server";
import { Firecrawl } from "firecrawl";
const firecrawl = new Firecrawl({
apiKey: process.env.FIRECRAWL_API_KEY,
});
export async function POST(request: Request) {
const { url } = await request.json();
const result = await firecrawl.scrape(url, {
formats: ["markdown"],
});
return NextResponse.json(result);
}
Test the route after deployment:
curl -X POST https://your-project.vercel.app/api/scrape \
-H "Content-Type: application/json" \
-d '{"url": "https://www.firecrawl.dev"}'
Search the web
Use search when your app needs current web results plus page content:
import { NextResponse } from "next/server";
import { Firecrawl } from "firecrawl";
const firecrawl = new Firecrawl({
apiKey: process.env.FIRECRAWL_API_KEY,
});
export async function POST(request: Request) {
const { query } = await request.json();
const results = await firecrawl.search(query, {
limit: 5,
scrapeOptions: {
formats: ["markdown"],
},
});
return NextResponse.json(results);
}
Interact with dynamic pages
Use interact when your app needs to click, scroll, or fill forms before extracting content.
import { NextResponse } from "next/server";
import { Firecrawl } from "firecrawl";
const firecrawl = new Firecrawl({
apiKey: process.env.FIRECRAWL_API_KEY,
});
export async function POST() {
const result = await firecrawl.scrape("https://news.ycombinator.com", {
formats: ["markdown"],
});
const scrapeId = result.metadata?.scrapeId;
if (!scrapeId) {
return NextResponse.json(
{ error: "No interactive scrape session was created" },
{ status: 500 }
);
}
const response = await firecrawl.interact(scrapeId, {
prompt: "Open the first story and summarize the page.",
});
await firecrawl.stopInteraction(scrapeId);
return NextResponse.json({ output: response.output });
}
Longer interactions can exceed short serverless timeouts. For production workflows that may take longer, run the work in a background job or use Firecrawl's async APIs with webhooks.
Use Firecrawl with the Vercel AI SDK
If you are building an agent with the Vercel AI SDK, install the Firecrawl AI SDK tools:
npm install firecrawl-aisdk ai
Then pass Firecrawl tools to your model. The Marketplace-installed FIRECRAWL_API_KEY is read from the environment.
The example below uses the Vercel AI Gateway model string format. Configure your AI SDK model provider or AI Gateway credentials separately.
import { generateText, stepCountIs } from "ai";
import { FirecrawlTools } from "firecrawl-aisdk";
const { text } = await generateText({
model: "anthropic/claude-sonnet-5.5",
tools: FirecrawlTools(),
stopWhen: stepCountIs(20),
prompt: "Search for recent Vercel AI SDK examples, scrape the best sources, and summarize them.",
});
console.log(text);
Next steps
Use Firecrawl in Vercel Functions with manual environment setup
Add Firecrawl tools to Vercel AI SDK agents
Convert webpages into Markdown, JSON, screenshots, and more
Search the web and get page content from results
Use Firecrawl with Laravel to search, scrape, and interact with web data using the REST API.
Prerequisites
- Laravel 10+ project
- A Firecrawl API key — get one free
Configuration
Add your API key to .env:
FIRECRAWL_API_KEY=fc-YOUR-API-KEY
Add the config entry to config/services.php:
'firecrawl' => [
'api_key' => env('FIRECRAWL_API_KEY'),
'base_url' => env('FIRECRAWL_API_URL', 'https://api.firecrawl.dev/v2'),
],
Create a service class
Create app/Services/FirecrawlService.php:
<?php
namespace App\Services;
use Illuminate\Support\Facades\Http;
class FirecrawlService
{
private string $apiKey;
private string $baseUrl;
public function __construct()
{
$this->apiKey = config('services.firecrawl.api_key');
$this->baseUrl = config('services.firecrawl.base_url');
}
public function search(string $query, int $limit = 5): array
{
$response = Http::withToken($this->apiKey)
->post("{$this->baseUrl}/search", [
'query' => $query,
'limit' => $limit,
]);
return $response->json();
}
public function scrape(string $url, array $options = []): array
{
$response = Http::withToken($this->apiKey)
->post("{$this->baseUrl}/scrape", array_merge(['url' => $url], $options));
return $response->json();
}
public function interact(string $url, string $prompt, ?string $followUp = null): array
{
// 1. Scrape to open a browser session
$scrapeResult = $this->scrape($url, ['formats' => ['markdown']]);
$scrapeId = $scrapeResult['data']['metadata']['scrapeId'];
// 2. Send first prompt
Http::withToken($this->apiKey)
->post("{$this->baseUrl}/scrape/{$scrapeId}/interact", [
'prompt' => $prompt,
]);
// 3. Send follow-up prompt
$result = null;
if ($followUp) {
$result = Http::withToken($this->apiKey)
->post("{$this->baseUrl}/scrape/{$scrapeId}/interact", [
'prompt' => $followUp,
])->json();
}
// 4. Close the session
Http::withToken($this->apiKey)
->delete("{$this->baseUrl}/scrape/{$scrapeId}/interact");
return $result ?? $scrapeResult;
}
}
Create a controller
Create app/Http/Controllers/FirecrawlController.php:
<?php
namespace App\Http\Controllers;
use App\Services\FirecrawlService;
use Illuminate\Http\Request;
class FirecrawlController extends Controller
{
public function __construct(private FirecrawlService $firecrawl) {}
public function search(Request $request)
{
$validated = $request->validate(['query' => 'required|string']);
return response()->json(
$this->firecrawl->search($validated['query'], $request->input('limit', 5))
);
}
public function scrape(Request $request)
{
$validated = $request->validate(['url' => 'required|url']);
return response()->json($this->firecrawl->scrape($validated['url']));
}
public function interact(Request $request)
{
$validated = $request->validate([
'url' => 'required|url',
'prompt' => 'required|string',
]);
return response()->json(
$this->firecrawl->interact(
$validated['url'],
$validated['prompt'],
$request->input('followUp')
)
);
}
}
Register routes
In routes/api.php:
use App\Http\Controllers\FirecrawlController;
Route::post('/search', [FirecrawlController::class, 'search']);
Route::post('/scrape', [FirecrawlController::class, 'scrape']);
Route::post('/interact', [FirecrawlController::class, 'interact']);
Test it
php artisan serve
# Search the web
curl -X POST http://localhost:8000/api/search \
-H "Content-Type: application/json" \
-d '{"query": "firecrawl web scraping"}'
# Scrape a page
curl -X POST http://localhost:8000/api/scrape \
-H "Content-Type: application/json" \
-d '{"url": "https://example.com"}'
# Interact with a page
curl -X POST http://localhost:8000/api/interact \
-H "Content-Type: application/json" \
-d '{"url": "https://www.amazon.com", "prompt": "Search for iPhone 16 Pro Max", "followUp": "Click on the first result and tell me the price"}'
Next steps
Search the web and get full page content
All scrape options including formats, actions, and proxies
Click, fill forms, and extract dynamic content
Complete REST API documentation
Use Firecrawl with Spring Boot to search, scrape, and interact with web data using the official Java SDK.
Prerequisites
- Java 17+ and Spring Boot 3+
- A Firecrawl API key — get one free
Add the dependency
dependencies {
implementation("com.firecrawl:firecrawl-java:1.18.0")
}
<dependency>
<groupId>com.firecrawl</groupId>
<artifactId>firecrawl-java</artifactId>
<version>1.18.0</version>
</dependency>
Configuration
Add your API key to application.properties:
firecrawl.api-key=${FIRECRAWL_API_KEY}
Or set it as an environment variable:
export FIRECRAWL_API_KEY=fc-YOUR-API-KEY
Create a configuration bean
Create FirecrawlConfig.java:
import com.firecrawl.client.FirecrawlClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class FirecrawlConfig {
@Bean
public FirecrawlClient firecrawlClient(
@Value("${firecrawl.api-key}") String apiKey) {
return FirecrawlClient.builder()
.apiKey(apiKey)
.build();
}
}
Create a REST controller
Create FirecrawlController.java:
import com.firecrawl.client.FirecrawlClient;
import com.firecrawl.models.Document;
import com.firecrawl.models.SearchData;
import com.firecrawl.models.SearchOptions;
import com.firecrawl.models.ScrapeOptions;
import com.firecrawl.models.BrowserExecuteResponse;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/api")
public class FirecrawlController {
private final FirecrawlClient firecrawl;
public FirecrawlController(FirecrawlClient firecrawl) {
this.firecrawl = firecrawl;
}
@PostMapping("/search")
public SearchData search(@RequestBody Map<String, Object> body) {
return firecrawl.search(
(String) body.get("query"),
SearchOptions.builder()
.limit((int) body.getOrDefault("limit", 5))
.build()
);
}
@PostMapping("/scrape")
public Map<String, Object> scrape(@RequestBody Map<String, String> body) {
Document doc = firecrawl.scrape(body.get("url"));
return Map.of(
"markdown", doc.getMarkdown(),
"metadata", doc.getMetadata()
);
}
@PostMapping("/interact")
public Map<String, Object> interact(@RequestBody Map<String, String> body) {
Document doc = firecrawl.scrape(body.get("url"),
ScrapeOptions.builder().formats(List.of((Object) "markdown")).build());
String scrapeId = (String) doc.getMetadata().get("scrapeId");
BrowserExecuteResponse response = firecrawl.interact(scrapeId,
body.getOrDefault("code", "const title = await page.title(); console.log(title);"));
firecrawl.stopInteractiveBrowser(scrapeId);
return Map.of("result", response.getStdout());
}
}
Run it
./gradlew bootRun
Test it
# Search the web
curl -X POST http://localhost:8080/api/search \
-H "Content-Type: application/json" \
-d '{"query": "firecrawl web scraping"}'
# Scrape a page
curl -X POST http://localhost:8080/api/scrape \
-H "Content-Type: application/json" \
-d '{"url": "https://example.com"}'
# Interact with a page
curl -X POST http://localhost:8080/api/interact \
-H "Content-Type: application/json" \
-d '{"url": "https://www.amazon.com", "code": "const title = await page.title(); console.log(title);"}'
Next steps
Search the web and get full page content
All scrape options including formats, actions, and proxies
Click, fill forms, and extract dynamic content
Full SDK reference with crawl, map, batch scrape, and more
Use Firecrawl as a tool inside Microsoft AutoGen multi-agent conversations.
Integrate Firecrawl with Microsoft AutoGen to give multi-agent conversations live web search, scrape, and crawl tools.
Setup
pip install -U "autogen-agentchat" "autogen-ext[openai]" firecrawl-py
Set your keys:
export FIRECRAWL_API_KEY=fc-YOUR-API-KEY
export OPENAI_API_KEY=sk-YOUR-OPENAI-KEY
Firecrawl as an AutoGen Tool
This example wraps Firecrawl's scrape and search as AutoGen function tools, then lets a single AssistantAgent use them to answer a question.
import asyncio
import os
from firecrawl import FirecrawlApp
from autogen_agentchat.agents import AssistantAgent
from autogen_agentchat.ui import Console
from autogen_ext.models.openai import OpenAIChatCompletionClient
firecrawl = FirecrawlApp(api_key=os.environ["FIRECRAWL_API_KEY"])
def scrape_url(url: str) -> str:
"""Scrape a URL and return clean markdown."""
result = firecrawl.scrape(url, formats=["markdown"])
return result.markdown or ""
def web_search(query: str, limit: int = 5) -> list[dict]:
"""Search the web and return the top results."""
result = firecrawl.search(query, limit=limit)
return [
{"title": r.title, "url": r.url, "snippet": r.description}
for r in result.web or []
]
async def main() -> None:
model = OpenAIChatCompletionClient(model="gpt-4o-mini")
researcher = AssistantAgent(
name="researcher",
model_client=model,
tools=[scrape_url, web_search],
system_message=(
"You are a web researcher. Use web_search to find candidate sources, "
"then scrape_url to read the most relevant ones. Cite URLs in your answer."
),
)
await Console(
researcher.run_stream(
task="What does Firecrawl's /agent endpoint do? Cite the docs."
)
)
if __name__ == "__main__":
asyncio.run(main())
Run it:
python researcher.py
Multi-Agent: Researcher + Writer
Hand Firecrawl output from a researcher agent to a writer agent in a round-robin team.
import asyncio
import os
from firecrawl import FirecrawlApp
from autogen_agentchat.agents import AssistantAgent
from autogen_agentchat.conditions import MaxMessageTermination
from autogen_agentchat.teams import RoundRobinGroupChat
from autogen_agentchat.ui import Console
from autogen_ext.models.openai import OpenAIChatCompletionClient
firecrawl = FirecrawlApp(api_key=os.environ["FIRECRAWL_API_KEY"])
def scrape_url(url: str) -> str:
result = firecrawl.scrape(url, formats=["markdown"])
return result.markdown or ""
def web_search(query: str, limit: int = 5) -> list[dict]:
result = firecrawl.search(query, limit=limit)
return [
{"title": r.title, "url": r.url, "snippet": r.description}
for r in result.web or []
]
async def main() -> None:
model = OpenAIChatCompletionClient(model="gpt-4o-mini")
researcher = AssistantAgent(
name="researcher",
model_client=model,
tools=[scrape_url, web_search],
system_message="Gather sources with web_search + scrape_url. Reply with bullet-point findings and URLs.",
)
writer = AssistantAgent(
name="writer",
model_client=model,
system_message="Turn the researcher's findings into a 200-word briefing with inline citations.",
)
team = RoundRobinGroupChat(
[researcher, writer],
termination_condition=MaxMessageTermination(max_messages=6),
)
await Console(team.run_stream(task="Write a briefing on Firecrawl's crawl endpoint."))
if __name__ == "__main__":
asyncio.run(main())
Notes
- Firecrawl's Python SDK is synchronous; AutoGen will call your wrappers inside its event loop without issues for small workloads. For heavy concurrent scraping, move calls off the main thread or use batch scrape.
- Replace
OpenAIChatCompletionClientwith any AutoGen-supported model client (Azure OpenAI, Anthropic viaautogen-ext, Ollama, etc.). Firecrawl is model-agnostic. - See the AutoGen docs for agent patterns beyond round-robin (selector, swarm, nested teams).
Use Firecrawl with Ruby on Rails to search, scrape, and interact with web data using the REST API.
Prerequisites
- Ruby 3.0+ and Rails 7+
- A Firecrawl API key — get one free
Configuration
Add your API key to your Rails credentials or environment:
export FIRECRAWL_API_KEY=fc-YOUR-API-KEY
Create a service
Create app/services/firecrawl_service.rb:
require "net/http"
require "json"
require "uri"
class FirecrawlService
BASE_URL = "https://api.firecrawl.dev/v2"
def initialize(api_key: ENV.fetch("FIRECRAWL_API_KEY"))
@api_key = api_key
end
def search(query, limit: 5)
post("/search", { query: query, limit: limit })
end
def scrape(url, **options)
post("/scrape", { url: url }.merge(options))
end
def interact(url, prompt, follow_up: nil)
# 1. Scrape to open a browser session
scrape_result = scrape(url, formats: ["markdown"])
scrape_id = scrape_result.dig("data", "metadata", "scrapeId")
# 2. Send first prompt
post("/scrape/#{scrape_id}/interact", { prompt: prompt })
# 3. Send follow-up prompt
result = nil
if follow_up
result = post("/scrape/#{scrape_id}/interact", { prompt: follow_up })
end
# 4. Close the session
delete("/scrape/#{scrape_id}/interact")
result || scrape_result
end
private
def post(endpoint, payload)
uri = URI("#{BASE_URL}#{endpoint}")
request = Net::HTTP::Post.new(uri)
request["Authorization"] = "Bearer #{@api_key}"
request["Content-Type"] = "application/json"
request.body = payload.to_json
response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|
http.request(request)
end
JSON.parse(response.body)
end
def delete(endpoint)
uri = URI("#{BASE_URL}#{endpoint}")
request = Net::HTTP::Delete.new(uri)
request["Authorization"] = "Bearer #{@api_key}"
Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|
http.request(request)
end
end
end
Create a controller
Generate a controller:
rails generate controller Firecrawl search scrape interact --skip-routes
Edit app/controllers/firecrawl_controller.rb:
class FirecrawlController < ApplicationController
skip_before_action :verify_authenticity_token
def search
service = FirecrawlService.new
result = service.search(params.require(:query), limit: params.fetch(:limit, 5).to_i)
render json: result
end
def scrape
service = FirecrawlService.new
result = service.scrape(params.require(:url))
render json: result
end
def interact
service = FirecrawlService.new
result = service.interact(
params.require(:url),
params.require(:prompt),
follow_up: params[:followUp]
)
render json: result
end
end
Add routes
In config/routes.rb:
Rails.application.routes.draw do
post "api/search", to: "firecrawl#search"
post "api/scrape", to: "firecrawl#scrape"
post "api/interact", to: "firecrawl#interact"
end
Test it
rails server
# Search the web
curl -X POST http://localhost:3000/api/search \
-H "Content-Type: application/json" \
-d '{"query": "firecrawl web scraping"}'
# Scrape a page
curl -X POST http://localhost:3000/api/scrape \
-H "Content-Type: application/json" \
-d '{"url": "https://example.com"}'
# Interact with a page
curl -X POST http://localhost:3000/api/interact \
-H "Content-Type: application/json" \
-d '{"url": "https://www.amazon.com", "prompt": "Search for iPhone 16 Pro Max", "followUp": "Click on the first result and tell me the price"}'
Next steps
Search the web and get full page content
All scrape options including formats, actions, and proxies
Click, fill forms, and extract dynamic content
Complete REST API documentation
Use Firecrawl with Remix to scrape, search, and interact with web data in your full-stack React app.
Prerequisites
- Remix project
- A Firecrawl API key — get one free
Install the SDK
npm install firecrawl
Add your API key to .env:
FIRECRAWL_API_KEY=fc-YOUR-API-KEY
Search the web
Use Firecrawl in an action to handle form submissions. Create app/routes/search.tsx:
import { json, type ActionFunctionArgs } from "@remix-run/node";
import { Form, useActionData } from "@remix-run/react";
import { Firecrawl } from "firecrawl";
const firecrawl = new Firecrawl({ apiKey: process.env.FIRECRAWL_API_KEY });
export async function action({ request }: ActionFunctionArgs) {
const formData = await request.formData();
const query = formData.get("query") as string;
const results = await firecrawl.search(query, { limit: 5 });
return json({ results: (results.web || []).map((r) => ({ title: r.title, url: r.url })) });
}
export default function SearchPage() {
const data = useActionData<typeof action>();
return (
<div>
<Form method="post">
<input name="query" placeholder="Search the web..." />
<button type="submit">Search</button>
</Form>
{data?.results?.map((r, i) => (
<div key={i}>
<a href={r.url}>{r.title})
</div>
))}
</div>
);
}
Scrape a page
Use Firecrawl in a loader to fetch data at request time. Create app/routes/scrape.tsx:
import { json, type LoaderFunctionArgs } from "@remix-run/node";
import { useLoaderData } from "@remix-run/react";
import { Firecrawl } from "firecrawl";
const firecrawl = new Firecrawl({ apiKey: process.env.FIRECRAWL_API_KEY });
export async function loader({ request }: LoaderFunctionArgs) {
const url = new URL(request.url);
const target = url.searchParams.get("url");
if (!target) return json({ markdown: null });
const result = await firecrawl.scrape(target);
return json({ markdown: result.markdown });
}
export default function ScrapePage() {
const { markdown } = useLoaderData<typeof loader>();
return (
<div>
<h1>Scraped Content</h1>
{markdown ? <pre>{markdown}</pre> : <p>Pass ?url= to scrape a page</p>}
</div>
);
}
Interact with a page
Use interact to control a live browser session — click buttons, fill forms, and extract dynamic content. Create app/routes/interact.tsx:
import { json, type ActionFunctionArgs } from "@remix-run/node";
import { Form, useActionData } from "@remix-run/react";
import { Firecrawl } from "firecrawl";
const firecrawl = new Firecrawl({ apiKey: process.env.FIRECRAWL_API_KEY });
export async function action({ request }: ActionFunctionArgs) {
const formData = await request.formData();
const url = formData.get("url") as string;
const result = await firecrawl.scrape(url, { formats: ['markdown'] });
const scrapeId = result.metadata?.scrapeId;
await firecrawl.interact(scrapeId, { prompt: 'Search for iPhone 16 Pro Max' });
const response = await firecrawl.interact(scrapeId, { prompt: 'Click on the first result and tell me the price' });
await firecrawl.stopInteraction(scrapeId);
return json({ output: response.output });
}
export default function InteractPage() {
const data = useActionData<typeof action>();
return (
<div>
<Form method="post">
<input name="url" placeholder="URL to interact with..." />
<button type="submit">Interact</button>
</Form>
{data?.output && <pre>{data.output}</pre>}
</div>
);
}
Next steps
All scrape options including formats, actions, and proxies
Search the web and get full page content
Click, fill forms, and extract dynamic content
Full SDK reference with crawl, map, batch scrape, and more
