Datadog API Client for Go

repository·master·Indexed 41 days ago

https://github.com/datadog/datadog-api-client-go

A high-level Go interface for Datadog API services featuring authentication support for OAuth2, API Keys, and Delegated Tokens, automatic retries with exponential backoff, and structured error handling via GenericOpenAPIError.

Tokens
842
Snippets
6
Records
6
Agent score
2%

What's inside Datadog

  1. Initialize a new APIClient

    master

    To interact with the Datadog API, you must create an APIClient using NewAPIClient. This requires a Configuration object which contains your credentials, HTTP client settings, and retry logic. It is recommended to share a single APIClient instance across your application.

    // Assuming Configuration is already initialized
    client := datadog.NewAPIClient(cfg)
  2. Use Delegated Token Authentication

    master

    If your workflow requires delegated token authentication, use UseDelegatedTokenAuth. This function checks the context.Context for ContextDelegatedToken credentials. If the token is missing or expired, it attempts to refresh it using the provided DelegatedTokenConfig and sets the Authorization: Bearer <token> header.

    err := datadog.UseDelegatedTokenAuth(ctx, &headerParams, delegatedTokenConfig)
    if err != nil {
        // Handle authentication error
    }
  3. Read and reuse response bodies

    master

    Because http.Response.Body is an io.ReadCloser that can only be read once, use ReadBody to read the content into a byte slice while automatically replacing the body with a new NopCloser. This allows you to inspect the body and still allow subsequent processes to read it.

    body, err := datadog.ReadBody(resp)
    if err != nil {
        // handle error
    }
    // resp.Body is still available for further reading
  4. Configure authentication keys in request headers

    master

    The SetAuthKeys function allows you to inject API keys (like DD-API-KEY or DD-APPLICATION-KEY) into the request headers by retrieving them from the provided context.Context. You pass the context, a pointer to a map for headers, and pairs of [key_name, header_name].

    // Example: Setting the API Key using the key name 'api-key' and header 'DD-API-KEY'
    datadog.SetAuthKeys(ctx, &headerParams, [2]string{"api-key", "DD-API-KEY"})
  5. Handle API errors with GenericOpenAPIError

    master

    When an API call fails, the client may return a GenericOpenAPIError. This error type provides structured access to the failure details:

    • ErrorMessage(): The human-readable error string.
    • Body(): The raw byte content of the error response.
    • Model(): The unpacked error model (if available).
    if err != nil {
        if apiErr, ok := err.(datadog.GenericOpenAPIError); ok {
            fmt.Printf("Error: %s\n", apiErr.ErrorMessage)
            fmt.Printf("Raw Body: %s\n", string(apiErr.Body()))
        }
    }
  6. Get the current client version

    master

    The Version constant provides the current version of the Datadog API client. This value is used in the User-Agent header for all API requests made by the client.

    package client
    
    import "fmt"
    
    func main() {
        fmt.Println("Client Version:", client.Version)
    }