如何安装(1/2)

Get started with Firecrawl in Go. Scrape, search, and interact with web data using the REST API.

Prerequisites

Search the web

Firecrawl works with Go through the REST API. Use net/http to make requests directly.

package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "io"
    "net/http"
    "os"
)

func main() {
    apiKey := os.Getenv("FIRECRAWL_API_KEY")

    body, _ := json.Marshal(map[string]interface{}{
        "query": "firecrawl web scraping",
        "limit": 5,
    })

    req, _ := http.NewRequest("POST", "https://api.firecrawl.dev/v2/search", bytes.NewReader(body))
    req.Header.Set("Authorization", "Bearer "+apiKey)
    req.Header.Set("Content-Type", "application/json")

    resp, err := http.DefaultClient.Do(req)
    if err != nil {
        fmt.Fprintf(os.Stderr, "request failed: %v\n", err)
        os.Exit(1)
    }
    defer resp.Body.Close()

    result, _ := io.ReadAll(resp.Body)
    fmt.Println(string(result))
}
{
  "success": true,
  "data": {
    "web": [
      {
        "url": "https://docs.firecrawl.dev",
        "title": "Firecrawl Documentation",
        "markdown": "# Firecrawl\n\nFirecrawl is a web scraping API..."
      }
    ]
  }
}

Scrape a page

body, _ := json.Marshal(map[string]string{
    "url": "https://example.com",
})

req, _ := http.NewRequest("POST", "https://api.firecrawl.dev/v2/scrape", bytes.NewReader(body))
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("Content-Type", "application/json")

resp, err := http.DefaultClient.Do(req)
if err != nil {
    fmt.Fprintf(os.Stderr, "request failed: %v\n", err)
    os.Exit(1)
}
defer resp.Body.Close()

result, _ := io.ReadAll(resp.Body)
fmt.Println(string(result))
{
  "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

body, _ := json.Marshal(map[string]interface{}{
    "url":     "https://www.amazon.com",
    "formats": []string{"markdown"},
})

req, _ := http.NewRequest("POST", "https://api.firecrawl.dev/v2/scrape", bytes.NewReader(body))
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("Content-Type", "application/json")

resp, err := http.DefaultClient.Do(req)
if err != nil {
    fmt.Fprintf(os.Stderr, "request failed: %v\n", err)
    os.Exit(1)
}
defer resp.Body.Close()

var scrapeResult map[string]interface{}
json.NewDecoder(resp.Body).Decode(&scrapeResult)

data := scrapeResult["data"].(map[string]interface{})
metadata := data["metadata"].(map[string]interface{})
scrapeId := metadata["scrapeId"].(string)
fmt.Println("scrapeId:", scrapeId)

Step 2 — Send interactions

// Search for a product
interactBody, _ := json.Marshal(map[string]string{
    "prompt": "Search for iPhone 16 Pro Max",
})

interactURL := fmt.Sprintf("https://api.firecrawl.dev/v2/scrape/%s/interact", scrapeId)
req, _ = http.NewRequest("POST", interactURL, bytes.NewReader(interactBody))
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("Content-Type", "application/json")

resp, err = http.DefaultClient.Do(req)
if err != nil {
    fmt.Fprintf(os.Stderr, "interact failed: %v\n", err)
    os.Exit(1)
}
defer resp.Body.Close()

result, _ := io.ReadAll(resp.Body)
fmt.Println(string(result))

// Click on the first result
interactBody, _ = json.Marshal(map[string]string{
    "prompt": "Click on the first result and tell me the price",
})

req, _ = http.NewRequest("POST", interactURL, bytes.NewReader(interactBody))
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("Content-Type", "application/json")

resp, err = http.DefaultClient.Do(req)
if err != nil {
    fmt.Fprintf(os.Stderr, "interact failed: %v\n", err)
    os.Exit(1)
}
defer resp.Body.Close()

result, _ = io.ReadAll(resp.Body)
fmt.Println(string(result))

Step 3 — Stop the session

req, _ = http.NewRequest("DELETE", interactURL, nil)
req.Header.Set("Authorization", "Bearer "+apiKey)

resp, err = http.DefaultClient.Do(req)
if err != nil {
    fmt.Fprintf(os.Stderr, "delete failed: %v\n", err)
    os.Exit(1)
}
defer resp.Body.Close()

fmt.Println("Session stopped")

Reusable helper

For repeated use, wrap the API in a small helper:

type FirecrawlClient struct {
    APIKey  string
    BaseURL string
    Client  *http.Client
}

func NewFirecrawlClient(apiKey string) *FirecrawlClient {
    return &FirecrawlClient{
        APIKey:  apiKey,
        BaseURL: "https://api.firecrawl.dev/v2",
        Client:  &http.Client{},
    }
}

func (fc *FirecrawlClient) post(endpoint string, payload interface{}) ([]byte, error) {
    body, err := json.Marshal(payload)
    if err != nil {
        return nil, err
    }

    req, err := http.NewRequest("POST", fc.BaseURL+endpoint, bytes.NewReader(body))
    if err != nil {
        return nil, err
    }
    req.Header.Set("Authorization", "Bearer "+fc.APIKey)
    req.Header.Set("Content-Type", "application/json")

    resp, err := fc.Client.Do(req)
    if err != nil {
        return nil, err
    }
    defer resp.Body.Close()

    return io.ReadAll(resp.Body)
}

func (fc *FirecrawlClient) Scrape(url string) ([]byte, error) {
    return fc.post("/scrape", map[string]string{"url": url})
}

func (fc *FirecrawlClient) Search(query string, limit int) ([]byte, error) {
    return fc.post("/search", map[string]interface{}{"query": query, "limit": limit})
}

A community Go SDK is available for the v1 API. See the Go SDK docs for details.

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

Get started with Firecrawl in PHP. Scrape, search, and interact with web data using the REST API.

Prerequisites

  • PHP 8.0+ with cURL extension
  • A Firecrawl API key — get one free

Search the web

Firecrawl works with PHP through the REST API using cURL.

<?php
$apiKey = getenv('FIRECRAWL_API_KEY');

$ch = curl_init('https://api.firecrawl.dev/v2/search');
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_HTTPHEADER => [
        'Authorization: Bearer ' . $apiKey,
        'Content-Type: application/json',
    ],
    CURLOPT_POSTFIELDS => json_encode([
        'query' => 'firecrawl web scraping',
        'limit' => 5,
    ]),
]);

$response = curl_exec($ch);
curl_close($ch);

$results = json_decode($response, true);
foreach ($results['data']['web'] as $result) {
    echo $result['title'] . ' - ' . $result['url'] . "\n";
}
{
  "success": true,
  "data": {
    "web": [
      {
        "url": "https://docs.firecrawl.dev",
        "title": "Firecrawl Documentation",
        "markdown": "# Firecrawl\n\nFirecrawl is a web scraping API..."
      }
    ]
  }
}

Scrape a page

<?php
$ch = curl_init('https://api.firecrawl.dev/v2/scrape');
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_HTTPHEADER => [
        'Authorization: Bearer ' . $apiKey,
        'Content-Type: application/json',
    ],
    CURLOPT_POSTFIELDS => json_encode([
        'url' => 'https://example.com',
    ]),
]);

$response = curl_exec($ch);
curl_close($ch);

$data = json_decode($response, true);
echo $data['data']['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

<?php
$ch = curl_init('https://api.firecrawl.dev/v2/scrape');
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_HTTPHEADER => [
        'Authorization: Bearer ' . $apiKey,
        'Content-Type: application/json',
    ],
    CURLOPT_POSTFIELDS => json_encode([
        'url' => 'https://www.amazon.com',
        'formats' => ['markdown'],
    ]),
]);

$response = curl_exec($ch);
curl_close($ch);

$scrapeResult = json_decode($response, true);
$scrapeId = $scrapeResult['data']['metadata']['scrapeId'];
echo "scrapeId: $scrapeId\n";

Step 2 — Send interactions

<?php
$interactUrl = "https://api.firecrawl.dev/v2/scrape/$scrapeId/interact";
$headers = [
    'Authorization: Bearer ' . $apiKey,
    'Content-Type: application/json',
];

// Search for a product
$ch = curl_init($interactUrl);
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_HTTPHEADER => $headers,
    CURLOPT_POSTFIELDS => json_encode([
        'prompt' => 'Search for iPhone 16 Pro Max',
    ]),
]);

$response = curl_exec($ch);
curl_close($ch);
echo $response . "\n";

// Click on the first result
$ch = curl_init($interactUrl);
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_HTTPHEADER => $headers,
    CURLOPT_POSTFIELDS => json_encode([
        'prompt' => 'Click on the first result and tell me the price',
    ]),
]);

$response = curl_exec($ch);
curl_close($ch);
echo $response . "\n";

Step 3 — Stop the session

<?php
$ch = curl_init($interactUrl);
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_CUSTOMREQUEST => 'DELETE',
    CURLOPT_HTTPHEADER => [
        'Authorization: Bearer ' . $apiKey,
    ],
]);

curl_exec($ch);
curl_close($ch);

echo "Session stopped\n";

Reusable helper class

For repeated use, wrap the API in a class:

<?php
class Firecrawl
{
    private string $apiKey;
    private string $baseUrl = 'https://api.firecrawl.dev/v2';

    public function __construct(string $apiKey)
    {
        $this->apiKey = $apiKey;
    }

    private function post(string $endpoint, array $payload): array
    {
        $ch = curl_init($this->baseUrl . $endpoint);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST => true,
            CURLOPT_HTTPHEADER => [
                'Authorization: Bearer ' . $this->apiKey,
                'Content-Type: application/json',
            ],
            CURLOPT_POSTFIELDS => json_encode($payload),
        ]);

        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($httpCode >= 400) {
            throw new \RuntimeException("Firecrawl API error: HTTP $httpCode");
        }

        return json_decode($response, true);
    }

    public function scrape(string $url, array $options = []): array
    {
        return $this->post('/scrape', array_merge(['url' => $url], $options));
    }

    public function search(string $query, int $limit = 5): array
    {
        return $this->post('/search', ['query' => $query, 'limit' => $limit]);
    }
}

// Usage
$app = new Firecrawl(getenv('FIRECRAWL_API_KEY'));
$result = $app->scrape('https://example.com');
echo $result['data']['markdown'];

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

Get started with Firecrawl in .NET. Scrape, search, and interact with web data using the REST API.

Prerequisites

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

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_KEY to 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

  1. Open the Firecrawl listing on the Vercel Marketplace.
  2. Click Connect Account.
  3. Choose the Firecrawl plan you want to use.
  4. Select the Vercel project that should receive the environment variable.
  5. 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

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