Skip to content
Docs
SDKs
Go

Go SDK (v1.0.0)

Access the Nstdata Crawl API from your Go applications. Scrape individual pages, submit remote asynchronous tasks, and crawl websites with configurable depth and page limits.

Retrieve content as Markdown, HTML, links, PDFs, screenshots, or raw bytes. The client accepts context-aware requests and has no third-party runtime dependencies. It calls the hosted Crawl API; MCP and a separate crawler deployment are not required.

GitHub repository (opens in a new tab) · Quick Start (opens in a new tab) · Usage guide (opens in a new tab)

Prerequisites

  • Go 1.20 or later. Use a currently maintained Go release in production.

  • A Nstdata API key (opens in a new tab) and available credits. Use the same Nstdata API key used for Crawl requests; there is no separate SDK key.

Installation

For a new application, create a directory and initialize a Go module. Skip module initialization if your project already has a go.mod file:

mkdir crawl-example
cd crawl-example
go mod init example.com/crawl-example

Install the SDK in your application module:

go get github.com/nstdata-ai/crawl-go@v1.0.0

Import the package as crawl. The package is a client library installed in your application, not a standalone server.

Authentication

Set the API key in the environment where you run the program.

macOS / Linux:

export NSTDATA_API_TOKEN='your-api-key'

Windows PowerShell:

$env:NSTDATA_API_TOKEN = "your-api-key"

The client authenticates requests with x-api-key. Keep the key in your server environment and out of source code and version control. A .env file is not loaded automatically by Go or this SDK; export the variable or explicitly load it in your application.

Quick Start

Save this complete example as main.go in your application module. It submits one page task, validates the result, and prints Markdown. Live service requests consume credits.

package main

import (
    "context"
    "errors"
    "fmt"
    "os"
    "strings"
    "time"

    crawl "github.com/nstdata-ai/crawl-go"
)

func main() {
    token := os.Getenv("NSTDATA_API_TOKEN")
    if strings.TrimSpace(token) == "" {
        fmt.Fprintln(os.Stderr, "Set NSTDATA_API_TOKEN in your environment.")
        os.Exit(1)
    }
    ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
    defer cancel()
    client := crawl.NewClient(token)

    if err := run(ctx, client); err != nil {
        var apiError *crawl.APIError
        switch {
        case errors.As(err, &apiError):
            fmt.Fprintf(os.Stderr, "API request failed: HTTP %d, code %d\n", apiError.StatusCode, apiError.Code)
        case errors.Is(err, context.DeadlineExceeded), errors.Is(err, context.Canceled):
            fmt.Fprintln(os.Stderr, "Local waiting stopped; preserve any saved task ID.")
        case errors.Is(err, crawl.ErrContentUnavailable):
            fmt.Fprintln(os.Stderr, "The requested content was not returned.")
        case errors.Is(err, crawl.ErrResponseTooLarge):
            fmt.Fprintln(os.Stderr, "The response exceeded the local byte limit.")
        default:
            fmt.Fprintln(os.Stderr, "Task, transport, or response validation failed.")
        }
        os.Exit(1)
    }
}

func run(ctx context.Context, client *crawl.Client) error {
    result, err := client.SubmitScrapeTaskSync(ctx, &crawl.ScrapeRequestDto{
        URL: "https://example.com/",
        Formats: []string{crawl.FormatMarkdown},
        OnlyMainContent: true,
        Timeout: 60000,
    })
    if err != nil {
        return err
    }
    if result == nil || result.Status != crawl.StatusCompleted || !result.Success || result.Data == nil {
        return errors.New("no successful completed content")
    }
    markdown, err := result.Data.GetMarkdown(ctx)
    if err != nil {
        return err
    }
    if result.Data.Truncated != nil && *result.Data.Truncated {
        fmt.Fprintln(os.Stderr, "Warning: returned content is partial.")
    }
    fmt.Println(markdown)
    return nil
}

Run it from the same application module:

go run .

SubmitScrapeTaskSync waits for one service response. GetMarkdown(ctx) reads inline content or fetches a referenced result when needed. An empty string with no error is valid empty content; missing content returns crawl.ErrContentUnavailable. A title can be stored in Metadata.Title without appearing in the filtered Markdown body.

Output Formats

FormatAccessResultUse
crawl.FormatMarkdowndata.GetMarkdown(ctx)string, errorText and LLM input
crawl.FormatHTMLdata.GetHtml(ctx)string, errorParse HTML
crawl.FormatLinksdata.Links[]stringCollect URLs
crawl.FormatPDFdata.GetPdf(ctx)[]byte, errorSave documents
crawl.FormatScreenshotdata.GetScreenshot(ctx)[]byte, errorCapture the page
crawl.FormatRawDatadata.GetRawData(ctx)[]byte, errorRead original bytes

Use Formats to select one or more outputs. Call getters only after validating that the task completed successfully and Data is available.

To request Markdown and HTML together, set Formats: []string{crawl.FormatMarkdown, crawl.FormatHTML}. Successful getter reads are cached. Raw data is bytes; it does not perform structured JSON extraction.

Core Workflows

The snippets below reuse the imports, client, deadline-bound context, and error handling from Quick Start. Replace the body of run(ctx, client) with one snippet at a time. Save returned task IDs before making follow-up requests. The Go SDK does not poll or paginate automatically.

Submit an asynchronous scrape

Submit once and save the returned ID:

submitted, err := client.SubmitScrapeTask(ctx, &crawl.ScrapeRequestDto{
    URL: "https://example.com/",
    Formats: []string{crawl.FormatMarkdown},
    OnlyMainContent: true,
})
if err != nil {
    return err
}
if submitted == nil || strings.TrimSpace(submitted.Id) == "" {
    return errors.New("no task ID returned")
}
fmt.Println("Save task ID:", submitted.Id)
return nil

In a later run, query the saved asynchronous task ID instead of submitting again:

taskID := "YOUR_TASK_ID"
result, err := client.GetScrapeTaskResult(ctx, taskID)
if err != nil {
    return err
}
if result == nil {
    return errors.New("missing task result")
}
if result.Status == crawl.StatusProcessing || result.Status == crawl.StatusScraping {
    fmt.Println("Still running; query the same saved task ID later.")
    return nil
}
if result.Status != crawl.StatusCompleted || !result.Success || result.Data == nil {
    return errors.New("no successful completed content")
}
markdown, err := result.Data.GetMarkdown(ctx)
if err != nil {
    return err
}
if result.Data.Truncated != nil && *result.Data.Truncated {
    fmt.Fprintln(os.Stderr, "Warning: returned content is partial.")
}
fmt.Println(markdown)
return nil

Polling intervals and overall waiting limits belong to your application. A synchronous response's optional Id is not a guarantee that it can later be queried as an asynchronous task. See asynchronous tasks (opens in a new tab).

Crawl a website

Start from one entry URL and bound link discovery:

submitted, err := client.SubmitCrawlTask(ctx, &crawl.CrawlRequestDto{
    URL: "https://example.com/",
    Formats: []string{crawl.FormatMarkdown},
    MaxDepth: 1,
    MaxPages: 2,
    OnlyMainContent: false,
})
if err != nil {
    return err
}
if submitted == nil || strings.TrimSpace(submitted.Id) == "" {
    return errors.New("no crawl ID returned")
}
fmt.Println("Save crawl ID:", submitted.Id)
return nil

MaxPages is an upper bound, not a promised result count. example.com demonstrates the API, not a multi-page website. Keeping OnlyMainContent: false retains navigation that may help discovery.

In a later run, check the saved ID and retrieve one batch of results:

crawlID := "YOUR_CRAWL_ID"
status, err := client.GetCrawlStatus(ctx, crawlID)
if err != nil {
    return err
}
if status == nil {
    return errors.New("missing crawl status")
}
if status.Status == crawl.StatusProcessing || status.Status == crawl.StatusScraping {
    fmt.Println("Still running; check the same saved crawl ID later.")
    return nil
}
if status.Status != crawl.StatusCompleted {
    return errors.New("crawl failed or expired")
}
pages, err := client.ListCrawlPages(ctx, crawlID, crawl.ListCrawlPagesOptions{Limit: 20})
if err != nil {
    return err
}
if pages == nil {
    return errors.New("missing page batch")
}
for _, page := range pages.Data {
    fmt.Println(page.Url, page.Status, page.Success)
    if page.Status != crawl.StatusCompleted || !page.Success || page.Data == nil {
        continue
    }
    markdown, err := page.Data.GetMarkdown(ctx)
    if err != nil {
        return err
    }
    if page.Data.Truncated != nil && *page.Data.Truncated {
        fmt.Fprintln(os.Stderr, "Warning: page content is partial.")
    }
    fmt.Println(markdown)
}
fmt.Println("Next cursor:", pages.NextCursor)
return nil

A completed crawl can contain unsuccessful pages; inspect each row. For the next batch, pass the returned NextCursor unchanged as AfterCursor with the same crawl ID. Stop when no next cursor is returned; an empty batch can still have a next cursor. Do not combine AfterCursor and BeforeCursor. Limit controls one result batch, not the crawl's MaxPages. Preserve IDs, cursors, and partial results if a later request fails. See site crawling (opens in a new tab).

Render JavaScript and run page actions

Use JsRender when the page needs JavaScript execution or interactions before extraction:

result, err := client.SubmitScrapeTaskSync(ctx, &crawl.ScrapeRequestDto{
    URL: "https://example.com/",
    Formats: []string{crawl.FormatMarkdown},
    OnlyMainContent: true,
    JsRender: &crawl.JsRenderDto{
        WaitForSelector: "h1",
        Actions: []crawl.ActionDto{
            {Type: crawl.ActionTypeScrollY, Y: 400},
            {Type: crawl.ActionTypeWait, Milliseconds: 1000},
        },
    },
    Timeout: 60000,
})
if err != nil {
    return err
}
if result == nil || result.Status != crawl.StatusCompleted || !result.Success || result.Data == nil {
    return errors.New("no successful completed content")
}
markdown, err := result.Data.GetMarkdown(ctx)
if err != nil {
    return err
}
if result.Data.Truncated != nil && *result.Data.Truncated {
    fmt.Fprintln(os.Stderr, "Warning: returned content is partial.")
}
fmt.Println(markdown)
return nil

Choose selectors and actions that match the target page. Actions execute in the Crawl service, not in a browser installed by the SDK on your machine. See rendering and request options (opens in a new tab).

Request Configuration

FieldPurpose
URL、FormatsTarget page and requested outputs
OnlyMainContentExtract the main content Always serialized. Defaults to false.
TargetSelector、RemoveSelectorsSelect a subtree or remove matching elements
IncludeTags、ExcludeTagsInclude or exclude tags
Headers、CookiesSupply request headers and cookies
ProxySelect the proxy country &crawl.ProxyDto{Country: "us"}
MobileUse mobile rendering
TimeoutService timeout in milliseconds (1,000–60,000)
JsRenderConfigure rendering, waits and page actions
MaxPages、MaxDepthLimit page count and discovery depth
IncludeUrls、ExcludeUrls、IgnoreQueryControl crawl URL matching

Go uses exported field names such as URL, Formats, OnlyMainContent, and JsRender; the SDK serializes them to the API's JSON field names.

JsRender.WaitFor accepts integer milliseconds from 1,000 to 30,000. Action milliseconds and coordinates must be finite integers. Other optional zero-valued fields are omitted. URL filter syntax and defaults are interpreted by the service; check the actual returned URLs.

Client and request controls

Configure the client before use:

client.HTTPClient = &http.Client{Timeout: 120 * time.Second}
client.MaxResponseBytes = 4 * 1024 * 1024

Import net/http when using the HTTP client configuration above. These assignments belong after crawl.NewClient(token) in main, not alongside a new unused client. All operations and content getters accept a context; use context.WithTimeout to bound a workflow or a particular operation.

A local timeout or context cancellation stops local waiting; it does not cancel the remote task. Redirects are refused. Configure client fields before sharing the client between goroutines, and do not mutate configuration during requests. See configuration and errors (opens in a new tab).

Results and Error Handling

A nil Truncated flag means unknown; it does not establish completeness. Preserve source URL, task ID where available, metadata, status, success, and truncation with downstream content. Keep API keys, signed storage references, and private target data out of logs.

Task failure can be a typed result with no HTTP error. Check both the result and the returned error. The SDK does not retry automatically. A submission timeout can leave its outcome unknown; inspect task history before deciding whether to submit again. Reuse saved asynchronous IDs instead of creating duplicate tasks.

Troubleshooting

SymptomResolution
Missing API keyLoad the key into the running process. Load .env explicitly if used.
Authentication or quota errorCheck Crawl access, key validity, API status and available credits.
Task still runningResume polling with the saved asynchronous task ID.
Missing Markdown or HTMLRequest that format, verify completion, success and data, then use the content getter.
Missing dynamic contentConfigure JavaScript rendering, waits and selectors for the target page.
Local timeoutCheck client and service timeout units. Save the task ID before retrying.
Truncated outputInspect the truncation flag on the returned data.
Response size limitDistinguish the local byte cap from service truncation. Review the configured download limit.
Fewer pages than expectedCheck URL filters, discovery, per-page outcomes and pagination. maxPages is a ceiling.
Missing go.modInstall the SDK inside your Go module.
Unknown fieldMatch exported names exactly, including Id, URL and Url.
Missing titleRead Metadata.Title when the filtered body omits it.

Method reference (opens in a new tab) · API routes (opens in a new tab) · Release notes (opens in a new tab) · Report an SDK issue (opens in a new tab)