CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/golang-github-com-data-dog--datadog-api-client-go-v2

Comprehensive Go API client for the Datadog monitoring and analytics platform with strongly-typed interfaces for all Datadog API v1 and v2 endpoints

Overview
Eval results
Files

common-package.mddocs/

Common Package (datadog)

The datadog package provides the core client infrastructure, configuration types, authentication mechanisms, and common utilities used by both v1 and v2 API packages.

Package Import

import "github.com/DataDog/datadog-api-client-go/v2/api/datadog"

Configuration

Configuration Type

type Configuration struct {
    Host             string
    Scheme           string
    DefaultHeader    map[string]string
    UserAgent        string
    Debug            bool
    Compress         bool
    Servers          ServerConfigurations
    OperationServers map[string]ServerConfigurations
    HTTPClient       *http.Client
    RetryConfiguration   RetryConfiguration
    DelegatedTokenConfig *DelegatedTokenConfig
}

Configuration stores all settings for the API client including:

  • Host - API host (e.g., "api.datadoghq.com")
  • Scheme - URL scheme ("https")
  • DefaultHeader - Default HTTP headers for all requests
  • UserAgent - User-Agent header value
  • Debug - Enable debug logging of HTTP requests/responses
  • Compress - Enable GZIP compression for requests/responses
  • Servers - Available server configurations
  • OperationServers - Per-operation server configurations
  • HTTPClient - Custom HTTP client for requests
  • RetryConfiguration - Automatic retry behavior settings
  • DelegatedTokenConfig - Cloud provider authentication configuration

Constructor

func NewConfiguration() *Configuration

Creates a new configuration with default settings.

Methods

func (c *Configuration) AddDefaultHeader(key string, value string)

Add a default HTTP header that will be included in all requests.

func (c *Configuration) GetUnstableOperations() []string

Returns a list of all unstable operations available in the API.

func (c *Configuration) IsUnstableOperation(operation string) bool

Check if a given operation is marked as unstable.

func (c *Configuration) IsUnstableOperationEnabled(operation string) bool

Check if an unstable operation is currently enabled.

func (c *Configuration) SetUnstableOperationEnabled(operation string, enabled bool) bool

Enable or disable access to an unstable operation. Returns true if the operation exists.

func (c *Configuration) ServerURL(index int, variables map[string]string) (string, error)

Construct a server URL from configuration index and variable substitutions.

func (c *Configuration) ServerURLWithContext(ctx context.Context, endpoint string) (string, error)

Construct a server URL using context values for server selection and variables.

RetryConfiguration Type

type RetryConfiguration struct {
    EnableRetry       bool
    BackOffMultiplier float64
    BackOffBase       float64
    HTTPRetryTimeout  time.Duration
    MaxRetries        int
}

Configuration for automatic request retry behavior:

  • EnableRetry - Enable retry on 429 (rate limit) and 5xx (server error) responses
  • BackOffMultiplier - Multiplier for exponential backoff between retries
  • BackOffBase - Base duration for backoff calculation
  • HTTPRetryTimeout - Total timeout duration for all retry attempts
  • MaxRetries - Maximum number of retry attempts (default: 3)

Example configuration:

config := datadog.NewConfiguration()
config.RetryConfiguration.EnableRetry = true
config.RetryConfiguration.MaxRetries = 5
config.RetryConfiguration.BackOffMultiplier = 2.0
config.RetryConfiguration.BackOffBase = 1.0
config.RetryConfiguration.HTTPRetryTimeout = 60 * time.Second

ServerConfiguration Type

type ServerConfiguration struct {
    URL         string
    Description string
    Variables   map[string]ServerVariable
}

Configuration for a server endpoint:

  • URL - Server URL template with variable placeholders
  • Description - Human-readable description of the server
  • Variables - Map of variable names to their definitions

ServerVariable Type

type ServerVariable struct {
    Description  string
    DefaultValue string
    EnumValues   []string
}

Variable definition for server URL templates:

  • Description - Variable description
  • DefaultValue - Default value if not specified
  • EnumValues - Allowed values for the variable

Service Type

type Service struct {
    Client *APIClient
}

Base service type that all API clients embed. Provides access to the shared APIClient instance for making HTTP requests.

API Client

APIClient Type

type APIClient struct {
    Cfg *Configuration
}

The main API client that manages communication with the Datadog API. In most cases, there should be only one shared APIClient instance.

Constructor

func NewAPIClient(cfg *Configuration) *APIClient

Creates a new API client with the given configuration.

Methods

func (c *APIClient) CallAPI(request *http.Request) (*http.Response, error)

Execute an HTTP request and return the response. Handles retry logic, compression, and error handling.

func (c *APIClient) Decode(v interface{}, b []byte, contentType string) error

Unmarshal response bytes into the provided interface based on content type.

func (c *APIClient) GetConfig() *Configuration

Returns the current configuration.

func (c *APIClient) GetDelegatedToken(ctx context.Context) (*DelegatedTokenCredentials, error)

Retrieve delegated token credentials from the configured provider (e.g., AWS).

func (c *APIClient) PrepareRequest(
    ctx context.Context,
    path string,
    method string,
    postBody interface{},
    headerParams map[string]string,
    queryParams map[string][]string,
    formParams map[string][]string,
    formFile *FormFile,
) (*http.Request, error)

Build an HTTP request from parameters. This is typically called internally by API client methods.

Authentication

Context Variables

Context keys used with context.WithValue() to pass authentication and configuration:

var (
    ContextOAuth2                    contextKey
    ContextBasicAuth                 contextKey
    ContextAccessToken               contextKey
    ContextAPIKeys                   contextKey
    ContextDelegatedToken            contextKey
    ContextAWSVariables              contextKey
    ContextHttpSignatureAuth         contextKey
    ContextServerIndex               contextKey
    ContextOperationServerIndices    contextKey
    ContextServerVariables           contextKey
    ContextOperationServerVariables  contextKey
)
  • ContextOAuth2 - OAuth2 token source for authentication
  • ContextBasicAuth - Basic authentication credentials
  • ContextAccessToken - OAuth2 access token string
  • ContextAPIKeys - API key authentication (primary method)
  • ContextDelegatedToken - Delegated token authentication
  • ContextAWSVariables - AWS credentials for authentication
  • ContextHttpSignatureAuth - HTTP signature authentication
  • ContextServerIndex - Server configuration index selection
  • ContextOperationServerIndices - Per-operation server index mapping
  • ContextServerVariables - Server variable overrides
  • ContextOperationServerVariables - Per-operation server variable overrides

APIKey Type

type APIKey struct {
    Key    string
    Prefix string
}

API key authentication configuration:

  • Key - The API key value
  • Prefix - Optional key prefix (e.g., "Bearer")

Example usage:

ctx := context.WithValue(
    context.Background(),
    datadog.ContextAPIKeys,
    map[string]datadog.APIKey{
        "apiKeyAuth": {Key: "YOUR_API_KEY"},
        "appKeyAuth": {Key: "YOUR_APP_KEY"},
    },
)

BasicAuth Type

type BasicAuth struct {
    UserName string
    Password string
}

Basic HTTP authentication configuration:

  • UserName - Username for basic auth
  • Password - Password for basic auth

DelegatedTokenConfig Type

type DelegatedTokenConfig struct {
    OrgUUID      string
    Provider     string
    ProviderAuth DelegatedTokenProvider
}

Configuration for cloud provider-based authentication:

  • OrgUUID - Datadog organization UUID
  • Provider - Cloud provider name (e.g., "aws")
  • ProviderAuth - Provider-specific authentication implementation

DelegatedTokenCredentials Type

type DelegatedTokenCredentials struct {
    OrgUUID        string
    DelegatedToken string
    DelegatedProof string
    Expiration     time.Time
}

Delegated authentication token credentials:

  • OrgUUID - Organization UUID
  • DelegatedToken - The delegated token
  • DelegatedProof - Cryptographic proof
  • Expiration - Token expiration time

Functions

func CallDelegatedTokenAuthenticate(
    ctx context.Context,
    config *DelegatedTokenConfig,
) (*DelegatedTokenCredentials, error)

Authenticate using delegated token configuration and return credentials.

func GetDelegatedToken(
    ctx context.Context,
    orgUUID string,
    delegatedAuthProof string,
) (*DelegatedTokenCredentials, error)

Retrieve a delegated token from the Datadog API.

func ParseDelegatedTokenResponse(
    tokenBytes []byte,
    orgUUID string,
    delegatedAuthProof string,
) (*DelegatedTokenCredentials, error)

Parse delegated token response bytes into credentials.

DelegatedTokenProvider Interface

type DelegatedTokenProvider interface {
    Authenticate(ctx context.Context, config *DelegatedTokenConfig) (*DelegatedTokenCredentials, error)
}

Interface that cloud provider authentication implementations must satisfy.

AWSAuth Type

type AWSAuth struct {
    AwsRegion string
}

AWS delegated authentication provider:

  • AwsRegion - AWS region for authentication

Methods

func (a *AWSAuth) Authenticate(
    ctx context.Context,
    config *DelegatedTokenConfig,
) (*DelegatedTokenCredentials, error)

Authenticate using AWS credentials and return delegated token credentials.

func (a *AWSAuth) GenerateAwsAuthData(
    orgUUID string,
    creds *Credentials,
) (*SigningData, error)

Generate AWS authentication data including signature.

func (a *AWSAuth) GetCredentials(ctx context.Context) *Credentials

Retrieve AWS credentials from environment or IAM role.

AWS Constants

const (
    AWSAccessKeyIdName     = "AWS_ACCESS_KEY_ID"
    AWSSecretAccessKeyName = "AWS_SECRET_ACCESS_KEY"
    AWSSessionTokenName    = "AWS_SESSION_TOKEN"
    ProviderAWS            = "aws"
)

AWS Supporting Types

type Credentials struct {
    AccessKeyID     string
    SecretAccessKey string
    SessionToken    string
}

AWS credentials container for delegated token authentication.

type SigningData struct {
    DelegatedAuthProof string
    OrgUUID            string
}

AWS request signing data for generating delegated authentication tokens.

Context Helper Functions

func NewDefaultContext(ctx context.Context) context.Context

Create a context with authentication credentials loaded from environment variables (DD_API_KEY, DD_APP_KEY, DD_SITE).

func SetAuthKeys(
    ctx context.Context,
    headerParams *map[string]string,
    keys ...[2]string,
)

Set authentication headers based on context values.

func UseDelegatedTokenAuth(
    ctx context.Context,
    headerParams *map[string]string,
    delegatedTokenConfig *DelegatedTokenConfig,
) error

Add delegated token authentication headers.

Nullable Types

Nullable wrappers for common types that can be null in JSON responses.

NullableBool

type NullableBool struct {
    // contains filtered or unexported fields
}

func NewNullableBool(val *bool) *NullableBool
func (v NullableBool) Get() *bool
func (v NullableBool) IsSet() bool
func (v NullableBool) MarshalJSON() ([]byte, error)
func (v *NullableBool) Set(val *bool)
func (v *NullableBool) UnmarshalJSON(src []byte) error
func (v *NullableBool) Unset()

NullableInt

type NullableInt struct {
    // contains filtered or unexported fields
}

func NewNullableInt(val *int) *NullableInt
func (v NullableInt) Get() *int
func (v NullableInt) IsSet() bool
func (v NullableInt) MarshalJSON() ([]byte, error)
func (v *NullableInt) Set(val *int)
func (v *NullableInt) UnmarshalJSON(src []byte) error
func (v *NullableInt) Unset()

NullableInt32

type NullableInt32 struct {
    // contains filtered or unexported fields
}

func NewNullableInt32(val *int32) *NullableInt32
func (v NullableInt32) Get() *int32
func (v NullableInt32) IsSet() bool
func (v NullableInt32) MarshalJSON() ([]byte, error)
func (v *NullableInt32) Set(val *int32)
func (v *NullableInt32) UnmarshalJSON(src []byte) error
func (v *NullableInt32) Unset()

NullableInt64

type NullableInt64 struct {
    // contains filtered or unexported fields
}

func NewNullableInt64(val *int64) *NullableInt64
func (v NullableInt64) Get() *int64
func (v NullableInt64) IsSet() bool
func (v NullableInt64) MarshalJSON() ([]byte, error)
func (v *NullableInt64) Set(val *int64)
func (v *NullableInt64) UnmarshalJSON(src []byte) error
func (v *NullableInt64) Unset()

NullableFloat32

type NullableFloat32 struct {
    // contains filtered or unexported fields
}

func NewNullableFloat32(val *float32) *NullableFloat32
func (v NullableFloat32) Get() *float32
func (v NullableFloat32) IsSet() bool
func (v NullableFloat32) MarshalJSON() ([]byte, error)
func (v *NullableFloat32) Set(val *float32)
func (v *NullableFloat32) UnmarshalJSON(src []byte) error
func (v *NullableFloat32) Unset()

NullableFloat64

type NullableFloat64 struct {
    // contains filtered or unexported fields
}

func NewNullableFloat64(val *float64) *NullableFloat64
func (v NullableFloat64) Get() *float64
func (v NullableFloat64) IsSet() bool
func (v NullableFloat64) MarshalJSON() ([]byte, error)
func (v *NullableFloat64) Set(val *float64)
func (v *NullableFloat64) UnmarshalJSON(src []byte) error
func (v *NullableFloat64) Unset()

NullableString

type NullableString struct {
    // contains filtered or unexported fields
}

func NewNullableString(val *string) *NullableString
func (v NullableString) Get() *string
func (v NullableString) IsSet() bool
func (v NullableString) MarshalJSON() ([]byte, error)
func (v *NullableString) Set(val *string)
func (v *NullableString) UnmarshalJSON(src []byte) error
func (v *NullableString) Unset()

NullableTime

type NullableTime struct {
    // contains filtered or unexported fields
}

func NewNullableTime(val *time.Time) *NullableTime
func (v NullableTime) Get() *time.Time
func (v NullableTime) IsSet() bool
func (v NullableTime) MarshalJSON() ([]byte, error)
func (v *NullableTime) Set(val *time.Time)
func (v *NullableTime) UnmarshalJSON(src []byte) error
func (v *NullableTime) Unset()

NullableList (Generic)

type NullableList[T any] struct {
    // contains filtered or unexported fields
}

func NewNullableList[T any](val *[]T) *NullableList[T]
func (v NullableList[T]) Get() *[]T
func (v NullableList[T]) IsSet() bool
func (v NullableList[T]) MarshalJSON() ([]byte, error)
func (v *NullableList[T]) Set(val *[]T)
func (v *NullableList[T]) UnmarshalJSON(src []byte) error
func (v *NullableList[T]) Unset()

Pointer Helper Functions

Helper functions to create pointers for optional parameters:

func PtrBool(v bool) *bool
func PtrInt(v int) *int
func PtrInt32(v int32) *int32
func PtrInt64(v int64) *int64
func PtrFloat32(v float32) *float32
func PtrFloat64(v float64) *float64
func PtrString(v string) *string
func PtrTime(v time.Time) *time.Time

Example usage:

optionalParams := datadogV2.NewListIncidentsOptionalParameters()
optionalParams.PageSize = datadog.PtrInt64(50)
optionalParams.Query = datadog.PtrString("state:active")

Model Type Patterns

All model types in datadogV1 and datadogV2 packages follow consistent patterns for creating and accessing data:

Constructor Functions

Every model type has a constructor function that requires all mandatory fields:

func New<ModelName>(requiredField1 Type1, requiredField2 Type2, ...) *ModelName

Example:

incident := datadogV2.NewIncidentCreateAttributes(
    true,                           // customerImpacted (required)
    "Database connection failure",  // title (required)
)

Setter Methods

Fluent setter methods for optional fields that return the model pointer for chaining:

func (o *ModelName) Set<FieldName>(v Type) *ModelName

Example:

incident.SetFields(fieldsMap)
incident.SetIncidentTypeUuid("incident-type-uuid")

Getter Methods

Safe getter methods that handle nil pointers:

func (o *ModelName) Get<FieldName>() Type
func (o *ModelName) Get<FieldName>Ok() (*Type, bool)

Example:

title := incident.GetTitle()              // Returns zero value if not set
title, ok := incident.GetTitleOk()       // Returns value and boolean indicating if set

Has Methods

Check if optional fields are set:

func (o *ModelName) Has<FieldName>() bool

Example:

if incident.HasCustomerImpactScope() {
    scope := incident.GetCustomerImpactScope()
    // Use scope
}

JSON Marshaling

All model types implement JSON marshaling and unmarshaling:

func (o ModelName) MarshalJSON() ([]byte, error)
func (o *ModelName) UnmarshalJSON(src []byte) error

Example Complete Usage

// Create with required fields
monitor := datadogV1.NewMonitor(
    "avg(last_5m):sum:system.cpu.user{*} > 80",
    datadogV1.MONITORTYPE_METRIC_ALERT,
)

// Set optional fields
monitor.SetName("High CPU Usage")
monitor.SetMessage("CPU is high @slack-alerts")
monitor.SetTags([]string{"env:production", "team:backend"})

// Check and get optional fields
if monitor.HasName() {
    name := monitor.GetName()
    fmt.Printf("Monitor name: %s\n", name)
}

// Safe access with Ok variant
if message, ok := monitor.GetMessageOk(); ok {
    fmt.Printf("Message: %s\n", *message)
}

Error Handling

GenericOpenAPIError Type

type GenericOpenAPIError struct {
    ErrorBody    []byte
    ErrorMessage string
    ErrorModel   interface{}
}

func (e GenericOpenAPIError) Body() []byte
func (e GenericOpenAPIError) Error() string
func (e GenericOpenAPIError) Model() interface{}

Generic error type for API errors:

  • ErrorBody - Raw error response body
  • ErrorMessage - Human-readable error message
  • ErrorModel - Unmarshaled error model (type depends on endpoint)

Methods:

  • Body() - Returns the raw response body
  • Error() - Returns the error message (implements error interface)
  • Model() - Returns the unmarshaled error model

Example usage:

resp, r, err := api.ListIncidents(ctx, params)
if err != nil {
    if apiErr, ok := err.(datadog.GenericOpenAPIError); ok {
        fmt.Printf("Error: %s\n", apiErr.Error())
        fmt.Printf("Raw body: %s\n", apiErr.Body())
        if model := apiErr.Model(); model != nil {
            // Type assert to specific error model
            if errorResponse, ok := model.(datadogV2.APIErrorResponse); ok {
                for _, error := range errorResponse.GetErrors() {
                    fmt.Printf("Error detail: %s\n", error.GetDetail())
                }
            }
        }
    }
    return err
}

Pagination

PaginationResult Type

type PaginationResult[T any] struct {
    Item  T
    Error error
}

Generic pagination helper returned by *WithPagination() methods:

  • Item - Current page item
  • Error - Error if pagination failed

Example usage:

optionalParams := datadogV2.NewListIncidentsOptionalParameters()
resp, _ := incidentsApi.ListIncidentsWithPagination(ctx, *optionalParams)

for paginationResult := range resp {
    if paginationResult.Error != nil {
        fmt.Fprintf(os.Stderr, "Error: %v\n", paginationResult.Error)
        break
    }
    // Process paginationResult.Item (type: datadogV2.IncidentsResponse)
    for _, incident := range paginationResult.Item.GetData() {
        fmt.Printf("Incident: %s\n", incident.Attributes.GetTitle())
    }
}

File Upload

FormFile Type

type FormFile struct {
    FormFileName string
    FileName     string
    FileBytes    []byte
}

Configuration for file upload in multipart/form-data requests:

  • FormFileName - Form field name
  • FileName - File name
  • FileBytes - File content

Utility Functions

JSON Marshaling

func Marshal(v interface{}) ([]byte, error)
func Unmarshal(data []byte, v interface{}) error
func NewEncoder(w io.Writer) *json.Encoder
func NewDecoder(r io.Reader) *json.Decoder

JSON marshaling and unmarshaling functions. The implementation may use either the standard library or goccy/go-json depending on build configuration.

HTTP Utilities

func ReadBody(response *http.Response) ([]byte, error)

Read and return the HTTP response body.

func GetUserAgent() string

Returns the User-Agent string for API requests.

func GetDelegatedTokenUrl(ctx context.Context) (string, error)

Get the delegated token endpoint URL.

Parameter Utilities

func ParameterToString(obj interface{}, collectionFormat string) string

Convert a parameter value to a string representation for use in query parameters or headers.

func ReplacePathParameter(path string, pathKey string, parameterValue string) string

Replace a path parameter placeholder with its value.

Object Utilities

func ContainsUnparsedObject(i interface{}) (bool, interface{})

Check if an object contains unparsed fields (for forward compatibility with newer API versions).

func DeleteKeys[V any](obj map[string]V, keysToDelete *[]string)

Delete specified keys from a map.

func Strlen(s string) int

Return the number of runes (not bytes) in a string.

Error Utilities

func ReportError(format string, a ...interface{}) error

Create a formatted error message.

Install with Tessl CLI

npx tessl i tessl/golang-github-com-data-dog--datadog-api-client-go-v2@2.54.0

docs

common-package.md

index.md

tile.json