Comprehensive Go API client for the Datadog monitoring and analytics platform with strongly-typed interfaces for all Datadog API v1 and v2 endpoints
The datadog package provides the core client infrastructure, configuration types, authentication mechanisms, and common utilities used by both v1 and v2 API packages.
import "github.com/DataDog/datadog-api-client-go/v2/api/datadog"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 requestsUserAgent - User-Agent header valueDebug - Enable debug logging of HTTP requests/responsesCompress - Enable GZIP compression for requests/responsesServers - Available server configurationsOperationServers - Per-operation server configurationsHTTPClient - Custom HTTP client for requestsRetryConfiguration - Automatic retry behavior settingsDelegatedTokenConfig - Cloud provider authentication configurationfunc NewConfiguration() *ConfigurationCreates a new configuration with default settings.
func (c *Configuration) AddDefaultHeader(key string, value string)Add a default HTTP header that will be included in all requests.
func (c *Configuration) GetUnstableOperations() []stringReturns a list of all unstable operations available in the API.
func (c *Configuration) IsUnstableOperation(operation string) boolCheck if a given operation is marked as unstable.
func (c *Configuration) IsUnstableOperationEnabled(operation string) boolCheck if an unstable operation is currently enabled.
func (c *Configuration) SetUnstableOperationEnabled(operation string, enabled bool) boolEnable 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.
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) responsesBackOffMultiplier - Multiplier for exponential backoff between retriesBackOffBase - Base duration for backoff calculationHTTPRetryTimeout - Total timeout duration for all retry attemptsMaxRetries - 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.Secondtype ServerConfiguration struct {
URL string
Description string
Variables map[string]ServerVariable
}Configuration for a server endpoint:
URL - Server URL template with variable placeholdersDescription - Human-readable description of the serverVariables - Map of variable names to their definitionstype ServerVariable struct {
Description string
DefaultValue string
EnumValues []string
}Variable definition for server URL templates:
Description - Variable descriptionDefaultValue - Default value if not specifiedEnumValues - Allowed values for the variabletype Service struct {
Client *APIClient
}Base service type that all API clients embed. Provides access to the shared APIClient instance for making HTTP requests.
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.
func NewAPIClient(cfg *Configuration) *APIClientCreates a new API client with the given configuration.
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) errorUnmarshal response bytes into the provided interface based on content type.
func (c *APIClient) GetConfig() *ConfigurationReturns 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.
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 authenticationContextBasicAuth - Basic authentication credentialsContextAccessToken - OAuth2 access token stringContextAPIKeys - API key authentication (primary method)ContextDelegatedToken - Delegated token authenticationContextAWSVariables - AWS credentials for authenticationContextHttpSignatureAuth - HTTP signature authenticationContextServerIndex - Server configuration index selectionContextOperationServerIndices - Per-operation server index mappingContextServerVariables - Server variable overridesContextOperationServerVariables - Per-operation server variable overridestype APIKey struct {
Key string
Prefix string
}API key authentication configuration:
Key - The API key valuePrefix - 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"},
},
)type BasicAuth struct {
UserName string
Password string
}Basic HTTP authentication configuration:
UserName - Username for basic authPassword - Password for basic authtype DelegatedTokenConfig struct {
OrgUUID string
Provider string
ProviderAuth DelegatedTokenProvider
}Configuration for cloud provider-based authentication:
OrgUUID - Datadog organization UUIDProvider - Cloud provider name (e.g., "aws")ProviderAuth - Provider-specific authentication implementationtype DelegatedTokenCredentials struct {
OrgUUID string
DelegatedToken string
DelegatedProof string
Expiration time.Time
}Delegated authentication token credentials:
OrgUUID - Organization UUIDDelegatedToken - The delegated tokenDelegatedProof - Cryptographic proofExpiration - Token expiration timefunc 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.
type DelegatedTokenProvider interface {
Authenticate(ctx context.Context, config *DelegatedTokenConfig) (*DelegatedTokenCredentials, error)
}Interface that cloud provider authentication implementations must satisfy.
type AWSAuth struct {
AwsRegion string
}AWS delegated authentication provider:
AwsRegion - AWS region for authenticationfunc (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) *CredentialsRetrieve AWS credentials from environment or IAM role.
const (
AWSAccessKeyIdName = "AWS_ACCESS_KEY_ID"
AWSSecretAccessKeyName = "AWS_SECRET_ACCESS_KEY"
AWSSessionTokenName = "AWS_SESSION_TOKEN"
ProviderAWS = "aws"
)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.
func NewDefaultContext(ctx context.Context) context.ContextCreate 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,
) errorAdd delegated token authentication headers.
Nullable wrappers for common types that can be null in JSON responses.
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()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()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()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()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()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()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()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()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()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.TimeExample usage:
optionalParams := datadogV2.NewListIncidentsOptionalParameters()
optionalParams.PageSize = datadog.PtrInt64(50)
optionalParams.Query = datadog.PtrString("state:active")All model types in datadogV1 and datadogV2 packages follow consistent patterns for creating and accessing data:
Every model type has a constructor function that requires all mandatory fields:
func New<ModelName>(requiredField1 Type1, requiredField2 Type2, ...) *ModelNameExample:
incident := datadogV2.NewIncidentCreateAttributes(
true, // customerImpacted (required)
"Database connection failure", // title (required)
)Fluent setter methods for optional fields that return the model pointer for chaining:
func (o *ModelName) Set<FieldName>(v Type) *ModelNameExample:
incident.SetFields(fieldsMap)
incident.SetIncidentTypeUuid("incident-type-uuid")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 setCheck if optional fields are set:
func (o *ModelName) Has<FieldName>() boolExample:
if incident.HasCustomerImpactScope() {
scope := incident.GetCustomerImpactScope()
// Use scope
}All model types implement JSON marshaling and unmarshaling:
func (o ModelName) MarshalJSON() ([]byte, error)
func (o *ModelName) UnmarshalJSON(src []byte) error// 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)
}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 bodyErrorMessage - Human-readable error messageErrorModel - Unmarshaled error model (type depends on endpoint)Methods:
Body() - Returns the raw response bodyError() - Returns the error message (implements error interface)Model() - Returns the unmarshaled error modelExample 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
}type PaginationResult[T any] struct {
Item T
Error error
}Generic pagination helper returned by *WithPagination() methods:
Item - Current page itemError - Error if pagination failedExample 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())
}
}type FormFile struct {
FormFileName string
FileName string
FileBytes []byte
}Configuration for file upload in multipart/form-data requests:
FormFileName - Form field nameFileName - File nameFileBytes - File contentfunc 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.DecoderJSON marshaling and unmarshaling functions. The implementation may use either the standard library or goccy/go-json depending on build configuration.
func ReadBody(response *http.Response) ([]byte, error)Read and return the HTTP response body.
func GetUserAgent() stringReturns the User-Agent string for API requests.
func GetDelegatedTokenUrl(ctx context.Context) (string, error)Get the delegated token endpoint URL.
func ParameterToString(obj interface{}, collectionFormat string) stringConvert a parameter value to a string representation for use in query parameters or headers.
func ReplacePathParameter(path string, pathKey string, parameterValue string) stringReplace a path parameter placeholder with its value.
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) intReturn the number of runes (not bytes) in a string.
func ReportError(format string, a ...interface{}) errorCreate 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