Skip to content

Authentication and Configuration

Igor Sazonov edited this page Sep 23, 2026 · 1 revision

Free operations require no key. Pro operations require a DefiLlama Pro API key and fail locally with *defillama.ProAPIKeyRequiredError if no key is configured. The SDK deliberately does not read environment variables on its own; the application decides how to load and protect the secret.1

Configure a Pro client

Keep the key outside source control, for example in DEFILLAMA_API_KEY, then pass it through WithAPIKey.

key := os.Getenv("DEFILLAMA_API_KEY")
if key == "" {
    return errors.New("DEFILLAMA_API_KEY is not set")
}

client, err := defillama.New(
    defillama.WithAPIKey(key),
    defillama.WithTimeout(10*time.Second),
)
if err != nil {
    return fmt.Errorf("create client: %w", err)
}

usage, err := client.Account().GetUsage(ctx)
if err != nil {
    return fmt.Errorf("get API usage: %w", err)
}
if credits, ok := usage.CreditsLeft(); ok {
    fmt.Printf("credits left: %.0f\n", credits)
}

DefiLlama's Pro API authenticates with the key as one escaped URL path segment: https://pro-api.llama.fi/{API_KEY}/<endpoint>. The client does not send the key as an HTTP header or query parameter. Its error URLs, response headers, response bodies, and nested HTTP errors are redacted before they reach the caller.1

Configuration options

Pass zero or more functional options to New.

Option Default Purpose
WithAPIKey(key) No key Enables Pro-only routes.
WithTimeout(d) 30s Sets the timeout on the SDK-created http.Client.
WithHTTPClient(client) SDK-created client Uses an application-owned client for proxies, tracing, TLS policy, or timeout control.
WithRetryPolicy(policy) One attempt Enables bounded retries for eligible GET failures.
WithUserAgent(value) defillama-go/<version> Replaces the request User-Agent.
WithPreferProForFree(true) false Routes Free operations through their official Pro equivalents when a key is present.
WithBaseURLsForTesting(map) Disabled Overrides origins for tests and advanced local mock-server setups.

New returns *ConfigError before making a request if an option is invalid. A nil option, a nil custom HTTP client, an empty user agent, a non-positive timeout, or a retry policy with fewer than one attempt are invalid.1

Set timeouts correctly

WithTimeout affects only the default HTTP client created by the SDK. When the application supplies WithHTTPClient, configure timeouts on that client and still use a deadline on every request context.

httpClient := &http.Client{Timeout: 8 * time.Second}
client, err := defillama.New(defillama.WithHTTPClient(httpClient))
if err != nil {
    return err
}

ctx, cancel := context.WithTimeout(context.Background(), 12*time.Second)
defer cancel()

The context is the final authority for a request. Cancellation and a deadline expiry stop retry waiting promptly.2

Configure retries

Retries are off by default. When enabled, they apply only to GET requests that fail due to a transient network error, HTTP 429, or HTTP 5xx. The SDK does not retry ordinary 4xx responses or JSON decode failures. Delay is exponential from BaseDelay, capped by MaxDelay, with optional ±50% jitter. A server Retry-After value is honored when it is longer than the calculated delay.2

client, err := defillama.New(
    defillama.WithAPIKey(os.Getenv("DEFILLAMA_API_KEY")),
    defillama.WithRetryPolicy(defillama.RetryPolicy{
        MaxAttempts: 3, // Includes the first attempt.
        BaseDelay:  250 * time.Millisecond,
        MaxDelay:   2 * time.Second,
        Jitter:     true,
    }),
)

MaxAttempts: 1 means no retry. Keep a finite context deadline because a policy does not replace application-level cancellation.

Choose Free or Pro routing for Free endpoints

By default, a Free method uses its route-specific public DefiLlama origin, even when the client has a Pro key. This is the least surprising behavior and is appropriate for applications that use both plans.

If an application intentionally wants the SDK to use DefiLlama's official Pro mapping for the 31 Free routes, opt in:

client, err := defillama.New(
    defillama.WithAPIKey(os.Getenv("DEFILLAMA_API_KEY")),
    defillama.WithPreferProForFree(true),
)

This option does not turn a missing key into a valid Pro configuration. It changes only routes that have an official Pro equivalent.1

Redirect and logging safety

Pro requests can follow same-origin redirects. A redirect to another origin is returned as an APIError rather than followed, preventing the path-embedded key from being sent to a different host. It is safe to record the SDK's error URL and HTTP error body in logs because the key is redacted; applications should still avoid logging their own raw configuration or environment values.1

References

Clone this wiki locally