firecrawl

package module
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 29, 2024 License: MIT Imports: 8 Imported by: 3

README

Firecrawl Go SDK

The Firecrawl Go SDK is a library that allows you to easily scrape and crawl websites, and output the data in a format ready for use with language models (LLMs). It provides a simple and intuitive interface for interacting with the Firecrawl API.

Installation

To install the Firecrawl Go SDK, you can

go get github.com/mendableai/firecrawl-go

Usage

  1. Get an API key from firecrawl.dev
  2. Set the API key as an environment variable named FIRECRAWL_API_KEY or pass it as a parameter to the FirecrawlApp class.

Here's an example of how to use the SDK with error handling:

import (
	"fmt"
	"log"

	"github.com/mendableai/firecrawl-go"
)

func main() {
	// Initialize the FirecrawlApp with your API key
	app, err := firecrawl.NewFirecrawlApp("YOUR_API_KEY")
	if err != nil {
		log.Fatalf("Failed to initialize FirecrawlApp: %v", err)
	}

	// Scrape a single URL
	scrapeResult, err := app.ScrapeURL("example.com", nil)
	if err != nil {
		log.Fatalf("Failed to scrape URL: %v", err)
	}
	fmt.Println(scrapeResult.Markdown)

	// Crawl a website
	idempotencyKey := uuid.New().String() // optional idempotency key
	crawlParams := &firecrawl.CrawlParams{
		ExcludePaths: []string{"blog/*"},
		MaxDepth:     prt(2),
	}
	crawlResult, err := app.CrawlURL("example.com", crawlParams, &idempotencyKey)
	if err != nil {
		log.Fatalf("Failed to crawl URL: %v", err)
	}
	jsonCrawlResult, err := json.MarshalIndent(crawlResult, "", "  ")
	if err != nil {
		log.Fatalf("Failed to marshal crawl result: %v", err)
	}
	fmt.Println(string(jsonCrawlResult))
}
Scraping a URL

To scrape a single URL with error handling, use the ScrapeURL method. It takes the URL as a parameter and returns the scraped data as a dictionary.

url := "https://example.com"
scrapedData, err := app.ScrapeURL(url, nil)
if err != nil {
	log.Fatalf("Failed to scrape URL: %v", err)
}
fmt.Println(scrapedData)
Extracting structured data from a URL

With LLM extraction, you can easily extract structured data from any URL. Here is how you to use it:

jsonSchema := map[string]any{
	"type": "object",
	"properties": map[string]any{
		"top": map[string]any{
			"type": "array",
			"items": map[string]any{
				"type": "object",
				"properties": map[string]any{
					"title":       map[string]string{"type": "string"},
					"points":      map[string]string{"type": "number"},
					"by":          map[string]string{"type": "string"},
					"commentsURL": map[string]string{"type": "string"},
				},
				"required": []string{"title", "points", "by", "commentsURL"},
			},
			"minItems":    5,
			"maxItems":    5,
			"description": "Top 5 stories on Hacker News",
		},
	},
	"required": []string{"top"},
}

llmExtractionParams := map[string]any{
	"extractorOptions": firecrawl.ExtractorOptions{
		ExtractionSchema: jsonSchema,
	},
}

scrapeResult, err := app.ScrapeURL("https://news.ycombinator.com", llmExtractionParams)
if err != nil {
	log.Fatalf("Failed to perform LLM extraction: %v", err)
}
fmt.Println(scrapeResult)
Crawling a Website

To crawl a website, use the CrawlUrl method. It takes the starting URL and optional parameters as arguments. The params argument allows you to specify additional options for the crawl job, such as the maximum number of pages to crawl, allowed domains, and the output format.

response, err := app.CrawlURL("https://roastmywebsite.ai", nil,nil)

if err != nil {
 log.Fatalf("Failed to crawl URL: %v", err)
}

fmt.Println(response)
Asynchronous Crawl

To initiate an asynchronous crawl of a website, utilize the AsyncCrawlURL method. This method requires the starting URL and optional parameters as inputs. The params argument enables you to define various settings for the asynchronous crawl, such as the maximum number of pages to crawl, permitted domains, and the output format. Upon successful initiation, this method returns an ID, which is essential for subsequently checking the status of the crawl.

response, err := app.AsyncCrawlURL("https://roastmywebsite.ai", nil, nil)

if err != nil {
  log.Fatalf("Failed to crawl URL: %v", err)
}

fmt.Println(response) 
Checking Crawl Status

To check the status of a crawl job, use the CheckCrawlStatus method. It takes the crawl ID as a parameter and returns the current status of the crawl job.

status, err := app.CheckCrawlStatus(id)
if err != nil {
	log.Fatalf("Failed to check crawl status: %v", err)
}
fmt.Println(status)
Canceling a Crawl Job

To cancel a crawl job, use the CancelCrawlJob method. It takes the job ID as a parameter and returns the cancellation status of the crawl job.

canceled, err := app.CancelCrawlJob(jobId)
if err != nil {
	log.Fatalf("Failed to cancel crawl job: %v", err)
}
fmt.Println(canceled)

Error Handling

The SDK handles errors returned by the Firecrawl API and raises appropriate exceptions. If an error occurs during a request, an exception will be raised with a descriptive error message.

Contributing

Contributions to the Firecrawl Go SDK are welcome! If you find any issues or have suggestions for improvements, please open an issue or submit a pull request on the GitHub repository.

License

The Firecrawl Go SDK is licensed under the MIT License. This means you are free to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the SDK, subject to the following conditions:

  • The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Please note that while this SDK is MIT licensed, it is part of a larger project which may be under different licensing terms. Always refer to the license information in the root directory of the main project for overall licensing details.

Documentation

Overview

Package firecrawl provides a client for interacting with the Firecrawl API.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type CancelCrawlJobResponse

type CancelCrawlJobResponse struct {
	Success bool   `json:"success"`
	Status  string `json:"status"`
}

CancelCrawlJobResponse represents the response for canceling a crawl job

type CrawlParams added in v1.0.0

type CrawlParams struct {
	ScrapeOptions      ScrapeParams `json:"scrapeOptions"`
	Webhook            *string      `json:"webhook,omitempty"`
	Limit              *int         `json:"limit,omitempty"`
	IncludePaths       []string     `json:"includePaths,omitempty"`
	ExcludePaths       []string     `json:"excludePaths,omitempty"`
	MaxDepth           *int         `json:"maxDepth,omitempty"`
	AllowBackwardLinks *bool        `json:"allowBackwardLinks,omitempty"`
	AllowExternalLinks *bool        `json:"allowExternalLinks,omitempty"`
	IgnoreSitemap      *bool        `json:"ignoreSitemap,omitempty"`
}

CrawlParams represents the parameters for a crawl request.

type CrawlResponse

type CrawlResponse struct {
	Success bool   `json:"success"`
	ID      string `json:"id,omitempty"`
	URL     string `json:"url,omitempty"`
}

CrawlResponse represents the response for crawling operations

type CrawlStatusResponse added in v1.0.0

type CrawlStatusResponse struct {
	Status      string               `json:"status"`
	Total       int                  `json:"total,omitempty"`
	Completed   int                  `json:"completed,omitempty"`
	CreditsUsed int                  `json:"creditsUsed,omitempty"`
	ExpiresAt   string               `json:"expiresAt,omitempty"`
	Next        *string              `json:"next,omitempty"`
	Data        []*FirecrawlDocument `json:"data,omitempty"`
}

CrawlStatusResponse (old JobStatusResponse) represents the response for checking crawl job

type FirecrawlApp

type FirecrawlApp struct {
	APIKey  string
	APIURL  string
	Client  *http.Client
	Version string
}

FirecrawlApp represents a client for the Firecrawl API.

func NewFirecrawlApp

func NewFirecrawlApp(apiKey, apiURL string) (*FirecrawlApp, error)

NewFirecrawlApp creates a new instance of FirecrawlApp with the provided API key and API URL. If the API key or API URL is not provided, it attempts to retrieve them from environment variables. If the API key is still not found, it returns an error.

Parameters:

  • apiKey: The API key for authenticating with the Firecrawl API. If empty, it will be retrieved from the FIRECRAWL_API_KEY environment variable.
  • apiURL: The base URL for the Firecrawl API. If empty, it will be retrieved from the FIRECRAWL_API_URL environment variable, defaulting to "https://api.firecrawl.dev".

Returns:

  • *FirecrawlApp: A new instance of FirecrawlApp configured with the provided or retrieved API key and API URL.
  • error: An error if the API key is not provided or retrieved.

func (*FirecrawlApp) AsyncCrawlURL added in v1.0.0

func (app *FirecrawlApp) AsyncCrawlURL(url string, params *CrawlParams, idempotencyKey *string) (*CrawlResponse, error)

CrawlURL starts a crawl job for the specified URL using the Firecrawl API.

Parameters:

  • url: The URL to crawl.
  • params: Optional parameters for the crawl request.
  • idempotencyKey: An optional idempotency key to ensure the request is idempotent.

Returns:

  • *CrawlResponse: The crawl response with id.
  • error: An error if the crawl request fails.

func (*FirecrawlApp) CancelCrawlJob

func (app *FirecrawlApp) CancelCrawlJob(ID string) (string, error)

CancelCrawlJob cancels a crawl job using the Firecrawl API.

Parameters:

  • ID: The ID of the crawl job to cancel.

Returns:

  • string: The status of the crawl job after cancellation.
  • error: An error if the crawl job cancellation request fails.

func (*FirecrawlApp) CheckCrawlStatus

func (app *FirecrawlApp) CheckCrawlStatus(ID string) (*CrawlStatusResponse, error)

CheckCrawlStatus checks the status of a crawl job using the Firecrawl API.

Parameters:

  • ID: The ID of the crawl job to check.

Returns:

  • *CrawlStatusResponse: The status of the crawl job.
  • error: An error if the crawl status check request fails.

func (*FirecrawlApp) CrawlURL

func (app *FirecrawlApp) CrawlURL(url string, params *CrawlParams, idempotencyKey *string, pollInterval ...int) (*CrawlStatusResponse, error)

CrawlURL starts a crawl job for the specified URL using the Firecrawl API.

Parameters:

  • url: The URL to crawl.
  • params: Optional parameters for the crawl request.
  • idempotencyKey: An optional idempotency key to ensure the request is idempotent (can be nil).
  • pollInterval: An optional interval (in seconds) at which to poll the job status. Default is 2 seconds.

Returns:

  • CrawlStatusResponse: The crawl result if the job is completed.
  • error: An error if the crawl request fails.

func (*FirecrawlApp) MapURL added in v1.0.0

func (app *FirecrawlApp) MapURL(url string, params *MapParams) (*MapResponse, error)

MapURL initiates a mapping operation for a URL using the Firecrawl API.

Parameters:

  • url: The URL to map.
  • params: Optional parameters for the mapping request.

Returns:

  • *MapResponse: The response from the mapping operation.
  • error: An error if the mapping request fails.

func (*FirecrawlApp) ScrapeURL

func (app *FirecrawlApp) ScrapeURL(url string, params *ScrapeParams) (*FirecrawlDocument, error)

ScrapeURL scrapes the content of the specified URL using the Firecrawl API.

Parameters:

  • url: The URL to be scraped.
  • params: Optional parameters for the scrape request, including extractor options for LLM extraction.

Returns:

  • *FirecrawlDocument or *FirecrawlDocumentV0: The scraped document data depending on the API version.
  • error: An error if the scrape request fails.

func (*FirecrawlApp) Search

func (app *FirecrawlApp) Search(query string, params *any) (any, error)

SearchURL searches for a URL using the Firecrawl API.

Parameters:

  • url: The URL to search for.
  • params: Optional parameters for the search request.
  • error: An error if the search request fails.

Search is not implemented in API version 1.0.0.

type FirecrawlDocument

type FirecrawlDocument struct {
	Markdown   string                     `json:"markdown,omitempty"`
	HTML       string                     `json:"html,omitempty"`
	RawHTML    string                     `json:"rawHtml,omitempty"`
	Screenshot string                     `json:"screenshot,omitempty"`
	Links      []string                   `json:"links,omitempty"`
	Metadata   *FirecrawlDocumentMetadata `json:"metadata,omitempty"`
}

FirecrawlDocument represents a document in Firecrawl

type FirecrawlDocumentMetadata

type FirecrawlDocumentMetadata struct {
	Title             *string   `json:"title,omitempty"`
	Description       *string   `json:"description,omitempty"`
	Language          *string   `json:"language,omitempty"`
	Keywords          *string   `json:"keywords,omitempty"`
	Robots            *string   `json:"robots,omitempty"`
	OGTitle           *string   `json:"ogTitle,omitempty"`
	OGDescription     *string   `json:"ogDescription,omitempty"`
	OGURL             *string   `json:"ogUrl,omitempty"`
	OGImage           *string   `json:"ogImage,omitempty"`
	OGAudio           *string   `json:"ogAudio,omitempty"`
	OGDeterminer      *string   `json:"ogDeterminer,omitempty"`
	OGLocale          *string   `json:"ogLocale,omitempty"`
	OGLocaleAlternate []*string `json:"ogLocaleAlternate,omitempty"`
	OGSiteName        *string   `json:"ogSiteName,omitempty"`
	OGVideo           *string   `json:"ogVideo,omitempty"`
	DCTermsCreated    *string   `json:"dctermsCreated,omitempty"`
	DCDateCreated     *string   `json:"dcDateCreated,omitempty"`
	DCDate            *string   `json:"dcDate,omitempty"`
	DCTermsType       *string   `json:"dctermsType,omitempty"`
	DCType            *string   `json:"dcType,omitempty"`
	DCTermsAudience   *string   `json:"dctermsAudience,omitempty"`
	DCTermsSubject    *string   `json:"dctermsSubject,omitempty"`
	DCSubject         *string   `json:"dcSubject,omitempty"`
	DCDescription     *string   `json:"dcDescription,omitempty"`
	DCTermsKeywords   *string   `json:"dctermsKeywords,omitempty"`
	ModifiedTime      *string   `json:"modifiedTime,omitempty"`
	PublishedTime     *string   `json:"publishedTime,omitempty"`
	ArticleTag        *string   `json:"articleTag,omitempty"`
	ArticleSection    *string   `json:"articleSection,omitempty"`
	SourceURL         *string   `json:"sourceURL,omitempty"`
	StatusCode        *int      `json:"statusCode,omitempty"`
	Error             *string   `json:"error,omitempty"`
}

FirecrawlDocumentMetadata represents metadata for a Firecrawl document

type MapParams added in v1.0.0

type MapParams struct {
	IncludeSubdomains *bool   `json:"includeSubdomains,omitempty"`
	Search            *string `json:"search,omitempty"`
	IgnoreSitemap     *bool   `json:"ignoreSitemap,omitempty"`
	Limit             *int    `json:"limit,omitempty"`
}

MapParams represents the parameters for a map request.

type MapResponse added in v1.0.0

type MapResponse struct {
	Success bool     `json:"success"`
	Links   []string `json:"links,omitempty"`
	Error   string   `json:"error,omitempty"`
}

MapResponse represents the response for mapping operations

type ScrapeParams added in v1.0.0

type ScrapeParams struct {
	Formats         []string           `json:"formats,omitempty"`
	Headers         *map[string]string `json:"headers,omitempty"`
	IncludeTags     []string           `json:"includeTags,omitempty"`
	ExcludeTags     []string           `json:"excludeTags,omitempty"`
	OnlyMainContent *bool              `json:"onlyMainContent,omitempty"`
	WaitFor         *int               `json:"waitFor,omitempty"`
	ParsePDF        *bool              `json:"parsePDF,omitempty"`
	Timeout         *int               `json:"timeout,omitempty"`
}

ScrapeParams represents the parameters for a scrape request.

type ScrapeResponse

type ScrapeResponse struct {
	Success bool               `json:"success"`
	Data    *FirecrawlDocument `json:"data,omitempty"`
}

ScrapeResponse represents the response for scraping operations

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL