> ## 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.

# .NET

> Le SDK .NET de Firecrawl est un wrapper de l’API Firecrawl qui vous permet de convertir facilement des sites web en markdown.

<div id="installation">
  ## Installation
</div>

Le SDK .NET officiel est maintenu dans le monorepo de Firecrawl à l’emplacement [apps/dot-net-sdk](https://github.com/firecrawl/firecrawl/tree/main/apps/dot-net-sdk).

Pour installer le SDK .NET de Firecrawl, ajoutez le package NuGet :

<Tabs>
  <Tab title=".NET CLI">
    ```bash theme={null}
    dotnet add package firecrawl-sdk
    ```
  </Tab>

  <Tab title="Gestionnaire de packages">
    ```powershell theme={null}
    Install-Package firecrawl-sdk
    ```
  </Tab>

  <Tab title="PackageReference">
    ```xml theme={null}
    <PackageReference Include="firecrawl-sdk" Version="1.0.0" />
    ```
  </Tab>
</Tabs>

<Note>Nécessite .NET 8.0 ou une version ultérieure.</Note>

<div id="usage">
  ## Utilisation
</div>

1. Obtenez une clé API sur [firecrawl.dev](https://firecrawl.dev)
2. Définissez la clé API comme variable d’environnement nommée `FIRECRAWL_API_KEY`, ou passez-la au constructeur `FirecrawlClient`

Voici un exemple rapide avec l’API actuelle du SDK :

```csharp theme={null}
using Firecrawl;
using Firecrawl.Models;

var client = new FirecrawlClient("fc-your-api-key");

// Scraper une seule page
var doc = await client.ScrapeAsync("https://firecrawl.dev",
    new ScrapeOptions { Formats = new List<object> { "markdown" } });

// Crawler un site web
var job = await client.CrawlAsync("https://firecrawl.dev",
    new CrawlOptions { Limit = 5 });

Console.WriteLine(doc.Markdown);
Console.WriteLine($"Crawled pages: {job.Data?.Count ?? 0}");
```

<div id="scraping-a-url">
  ### Scraping d’une URL
</div>

Pour effectuer le scraping d’une seule URL, utilisez la méthode `ScrapeAsync`.

```csharp theme={null}
using Firecrawl.Models;

var doc = await client.ScrapeAsync("https://firecrawl.dev",
    new ScrapeOptions
    {
        Formats = new List<object> { "markdown", "html" },
        OnlyMainContent = true,
        WaitFor = 5000
    });

Console.WriteLine(doc.Markdown);
Console.WriteLine(doc.Metadata?["title"]);
```

<div id="json-extraction">
  #### Extraction de JSON
</div>

Extrayez des données JSON structurées avec `JsonFormat` via le point de terminaison `scrape` :

```csharp theme={null}
using Firecrawl.Models;

var jsonFmt = new JsonFormat
{
    Prompt = "Extract the product name and price",
    Schema = new Dictionary<string, object>
    {
        ["type"] = "object",
        ["properties"] = new Dictionary<string, object>
        {
            ["name"] = new Dictionary<string, object> { ["type"] = "string" },
            ["price"] = new Dictionary<string, object> { ["type"] = "number" }
        }
    }
};

var doc = await client.ScrapeAsync("https://example.com/product",
    new ScrapeOptions
    {
        Formats = new List<object> { jsonFmt }
    });

Console.WriteLine(doc.Json);
```

<div id="crawling-a-website">
  ### Effectuer un crawl sur un site web
</div>

Pour effectuer un crawl sur un site web et attendre la fin de l'opération, utilisez `CrawlAsync`. Cette méthode gère automatiquement l'interrogation et la pagination.

```csharp theme={null}
using Firecrawl.Models;

var job = await client.CrawlAsync("https://firecrawl.dev",
    new CrawlOptions
    {
        Limit = 50,
        MaxDiscoveryDepth = 3,
        ScrapeOptions = new ScrapeOptions
        {
            Formats = new List<object> { "markdown" }
        }
    });

Console.WriteLine($"Status: {job.Status}");
Console.WriteLine($"Progress: {job.Completed}/{job.Total}");

if (job.Data != null)
{
    foreach (var page in job.Data)
    {
        Console.WriteLine(page.Metadata?["sourceURL"]);
    }
}
```

<div id="start-a-crawl">
  ### Démarrer un crawl
</div>

Lancez une tâche sans attendre avec `StartCrawlAsync`.

```csharp theme={null}
using Firecrawl.Models;

var start = await client.StartCrawlAsync("https://firecrawl.dev",
    new CrawlOptions { Limit = 100 });

Console.WriteLine($"Job ID: {start.Id}");
```

<div id="checking-crawl-status">
  ### Vérifier l’état du crawl
</div>

Consultez la progression du crawl avec `GetCrawlStatusAsync`.

```csharp theme={null}
var status = await client.GetCrawlStatusAsync(start.Id!);
Console.WriteLine($"Status: {status.Status}");
Console.WriteLine($"Progress: {status.Completed}/{status.Total}");
```

<div id="cancelling-a-crawl">
  ### Annuler un crawl
</div>

Annulez un crawl en cours avec `CancelCrawlAsync`.

```csharp theme={null}
var result = await client.CancelCrawlAsync(start.Id!);
Console.WriteLine(result);
```

<div id="mapping-a-website">
  ### Cartographier un site web
</div>

Découvrez les liens d’un site avec `MapAsync`.

```csharp theme={null}
using Firecrawl.Models;

var data = await client.MapAsync("https://firecrawl.dev",
    new MapOptions
    {
        Limit = 100,
        Search = "blog"
    });

if (data.Links != null)
{
    foreach (var link in data.Links)
    {
        Console.WriteLine(link);
    }
}
```

<div id="searching-the-web">
  ### Recherche sur le Web
</div>

Effectuez une recherche avec des paramètres facultatifs via `SearchAsync`.

```csharp theme={null}
using Firecrawl.Models;

var results = await client.SearchAsync("firecrawl web scraping",
    new SearchOptions
    {
        Limit = 10,
        Location = "US"
    });

if (results.Web != null)
{
    foreach (var hit in results.Web)
    {
        Console.WriteLine($"{hit.Title} - {hit.Url}");
    }
}
```

<div id="batch-scraping">
  ### Scraping par lots
</div>

Scrapez plusieurs URL en parallèle à l’aide de `BatchScrapeAsync`. Cette méthode gère automatiquement l’interrogation et la pagination.

```csharp theme={null}
using Firecrawl.Models;

var urls = new List<string>
{
    "https://firecrawl.dev",
    "https://firecrawl.dev/blog"
};

var job = await client.BatchScrapeAsync(urls,
    new BatchScrapeOptions
    {
        Options = new ScrapeOptions
        {
            Formats = new List<object> { "markdown" }
        }
    });

if (job.Data != null)
{
    foreach (var doc in job.Data)
    {
        Console.WriteLine(doc.Markdown);
    }
}
```

<div id="batch-scrape-with-idempotency-key">
  #### Extraction par lot avec clé d’idempotence
</div>

Pour éviter que des requêtes en double ne soient traitées, fournissez une `IdempotencyKey` :

```csharp theme={null}
var job = await client.BatchScrapeAsync(urls,
    new BatchScrapeOptions
    {
        IdempotencyKey = "my-unique-key",
        Options = new ScrapeOptions
        {
            Formats = new List<object> { "markdown" }
        }
    });
```

<div id="usage-metrics">
  ### Utilisation & métriques
</div>

Vérifier la concurrence et les crédits restants :

```csharp theme={null}
using Firecrawl.Models;

var concurrency = await client.GetConcurrencyAsync();
Console.WriteLine($"Concurrency: {concurrency.Current}/{concurrency.MaxConcurrency}");

var credits = await client.GetCreditUsageAsync();
Console.WriteLine($"Remaining credits: {credits.RemainingCredits}");
```

<div id="async-support">
  ## Compatibilité async
</div>

Toutes les méthodes du SDK .NET sont async par défaut et renvoient `Task<T>`. Elles prennent également en charge `CancellationToken` pour permettre une annulation coopérative.

```csharp theme={null}
using Firecrawl.Models;

using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30));

var doc = await client.ScrapeAsync("https://example.com",
    new ScrapeOptions
    {
        Formats = new List<object> { "markdown" }
    },
    cancellationToken: cts.Token);

Console.WriteLine(doc.Markdown);
```

<div id="configuration">
  ## Configuration
</div>

Le constructeur `FirecrawlClient` accepte les options suivantes :

| Option          | Type          | Par défaut                                           | Description                                                   |
| --------------- | ------------- | ---------------------------------------------------- | ------------------------------------------------------------- |
| `apiKey`        | `string?`     | variable d'environnement `FIRECRAWL_API_KEY`         | Votre clé API Firecrawl                                       |
| `apiUrl`        | `string?`     | `https://api.firecrawl.dev` (ou `FIRECRAWL_API_URL`) | URL de base de l'API                                          |
| `timeout`       | `TimeSpan?`   | 5 minutes                                            | Délai d'expiration de la requête HTTP                         |
| `maxRetries`    | `int`         | `3`                                                  | Nouvelles tentatives automatiques en cas d'échecs temporaires |
| `backoffFactor` | `double`      | `0.5`                                                | Facteur de backoff exponentiel en secondes                    |
| `httpClient`    | `HttpClient?` | Créé à partir de `timeout`                           | Instance HttpClient préconfigurée                             |

```csharp theme={null}
using Firecrawl;

var client = new FirecrawlClient(
    apiKey: "fc-your-api-key",
    apiUrl: "https://api.firecrawl.dev",
    timeout: TimeSpan.FromMinutes(5),
    maxRetries: 3,
    backoffFactor: 0.5);
```

<div id="custom-http-client">
  ### Client HTTP personnalisé
</div>

Vous pouvez transmettre un `HttpClient` préconfiguré pour contrôler le pool de connexions, les proxys, les gestionnaires de messages et toute autre fonctionnalité de `HttpClient`. Lorsqu’il est fourni, le paramètre `timeout` est ignoré au profit de la configuration du client lui-même.

```csharp theme={null}
using Firecrawl;

var handler = new HttpClientHandler
{
    Proxy = new WebProxy("http://proxy.example.com:8080"),
    UseProxy = true
};

var httpClient = new HttpClient(handler)
{
    Timeout = TimeSpan.FromSeconds(60)
};

var client = new FirecrawlClient(
    apiKey: "fc-your-api-key",
    httpClient: httpClient);
```

<div id="environment-variable-configuration">
  ### Configuration des variables d'environnement
</div>

Le SDK détermine sa configuration à partir des variables d'environnement lorsque les paramètres du constructeur ne sont pas fournis :

```csharp theme={null}
// Utilise les variables d'environnement FIRECRAWL_API_KEY et FIRECRAWL_API_URL
var client = new FirecrawlClient();
```

<div id="error-handling">
  ## Gestion des erreurs
</div>

Le SDK génère des exceptions spécifiques dans `Firecrawl.Exceptions`.

```csharp theme={null}
using Firecrawl.Exceptions;
using Firecrawl.Models;

try
{
    var doc = await client.ScrapeAsync("https://example.com");
}
catch (AuthenticationException ex)
{
    Console.Error.WriteLine($"Auth failed: {ex.Message}");
}
catch (RateLimitException ex)
{
    Console.Error.WriteLine($"Rate limited: {ex.Message}");
}
catch (JobTimeoutException ex)
{
    Console.Error.WriteLine($"Job {ex.JobId} timed out after {ex.TimeoutSeconds}s");
}
catch (FirecrawlException ex)
{
    Console.Error.WriteLine($"Error {ex.StatusCode}: {ex.Message}");
}
```

La hiérarchie des exceptions :

| Exception                 | Code HTTP | Quand                                                                       |
| ------------------------- | --------- | --------------------------------------------------------------------------- |
| `AuthenticationException` | 401       | Clé API invalide ou manquante                                               |
| `RateLimitException`      | 429       | Trop de requêtes                                                            |
| `JobTimeoutException`     | —         | La tâche asynchrone (crawl/extraction par lot) n’a pas été terminée à temps |
| `FirecrawlException`      | variable  | Exception de base pour toutes les autres erreurs de l’API                   |

Les échecs transitoires (408, 409, 502 et autres erreurs 5xx) sont automatiquement retentés avec un backoff exponentiel avant qu’une exception ne soit levée.

> Êtes-vous un agent IA ayant besoin d’une clé API Firecrawl ? Consultez [firecrawl.dev/agent-onboarding/SKILL.md](https://www.firecrawl.dev/agent-onboarding/SKILL.md) pour les instructions d’intégration automatisée.
