### Install Datadog API Client (Maven) Source: https://github.com/datadog/datadog-api-client-java/blob/master/README.md Installs the Datadog API client library to your local Maven repository. Ensure Java 1.8+ and Maven are installed. ```shell mvn clean install ``` -------------------------------- ### Configure Proxy Settings for ApiClient in Java Source: https://context7.com/datadog/datadog-api-client-java/llms.txt Set up a proxy for the ApiClient by providing a custom ClientConfig with ApacheConnectorProvider. This example demonstrates configuring a local proxy. ```java import org.glassfish.jersey.apache.connector.ApacheConnectorProvider; import org.glassfish.jersey.client.ClientConfig; import org.glassfish.jersey.client.ClientProperties; import com.datadog.api.client.ApiClient; import com.datadog.api.client.ApiException; import com.datadog.api.client.v1.api.DashboardsApi; import com.datadog.api.client.v1.model.DashboardSummary; public class ProxyExample { public static void main(String[] args) { ApiClient defaultClient = ApiClient.getDefaultApiClient(); ClientConfig clientConfig = defaultClient .getClientConfig() .connectorProvider(new ApacheConnectorProvider()); clientConfig.property(ClientProperties.PROXY_URI, "http://127.0.0.1:8080"); defaultClient.setClientConfig(clientConfig); DashboardsApi apiInstance = new DashboardsApi(defaultClient); try { DashboardSummary result = apiInstance.listDashboards(); System.out.println(result); } catch (ApiException e) { System.err.println("Status code: " + e.getCode()); System.err.println("Reason: " + e.getResponseBody()); } } } ``` -------------------------------- ### Configure Proxy with ApacheConnectorProvider Source: https://github.com/datadog/datadog-api-client-java/blob/master/README.md Provide a custom connectorProvider implementation to ClientConfig to use a proxy. This example demonstrates using ApacheConnectorProvider. ```java import org.glassfish.jersey.apache.connector.ApacheConnectorProvider; import org.glassfish.jersey.client.ClientConfig; import org.glassfish.jersey.client.ClientProperties; import com.datadog.api.client.ApiClient; import com.datadog.api.client.ApiException; import com.datadog.api.client.v1.api.DashboardsApi; import com.datadog.api.client.v1.model.DashboardSummary; public class ProxyExample { public static void main( String[] args ) { ApiClient defaultClient = ApiClient.getDefaultApiClient(); ClientConfig clientConfig = defaultClient.getClientConfig().connectorProvider(new ApacheConnectorProvider()); clientConfig.property(ClientProperties.PROXY_URI, "http://127.0.0.1:80"); defaultClient.setClientConfig(clientConfig); DashboardsApi apiInstance = new DashboardsApi(defaultClient); try { DashboardSummary result = apiInstance.listDashboards(); System.out.println(result); } catch (ApiException e) { System.err.println("Exception when calling DashboardsApi#listDashboards"); System.err.println("Status code: " + e.getCode()); System.err.println("Reason: " + e.getResponseBody()); System.err.println("Response headers: " + e.getResponseHeaders()); e.printStackTrace(); } } } ``` -------------------------------- ### Create a Monitor Configuration Policy (v2) Source: https://context7.com/datadog/datadog-api-client-java/llms.txt This example demonstrates how to create a monitor configuration policy using the v2 MonitorsApi. It enforces tag requirements for monitors. Ensure proper error handling for API calls. ```java import com.datadog.api.client.ApiClient; import com.datadog.api.client.ApiException; import com.datadog.api.client.v2.api.MonitorsApi; import com.datadog.api.client.v2.model.*; import java.util.Arrays; public class CreateMonitorConfigPolicyExample { public static void main(String[] args) { ApiClient defaultClient = ApiClient.getDefaultApiClient(); MonitorsApi apiInstance = new MonitorsApi(defaultClient); MonitorConfigPolicyCreateRequest body = new MonitorConfigPolicyCreateRequest() .data( new MonitorConfigPolicyCreateData() .attributes( new MonitorConfigPolicyAttributeCreateRequest() .policyType(MonitorConfigPolicyType.TAG) .policy( new MonitorConfigPolicyPolicyCreateRequest( new MonitorConfigPolicyTagPolicyCreateRequest() .tagKey("env") .tagKeyRequired(true) .validTagValues(Arrays.asList("prod", "staging", "dev"))))) .type(MonitorConfigPolicyResourceType.MONITOR_CONFIG_POLICY)); try { MonitorConfigPolicyResponse result = apiInstance.createMonitorConfigPolicy(body); System.out.println("Policy ID: " + result.getData().getId()); } catch (ApiException e) { System.err.println("Status code: " + e.getCode()); System.err.println("Reason: " + e.getResponseBody()); e.printStackTrace(); } } } ``` -------------------------------- ### Create Datadog Monitor Source: https://github.com/datadog/datadog-api-client-java/blob/master/README.md Example of creating a Datadog monitor using the Java API client. Requires importing necessary classes and handling potential API exceptions. ```java import com.datadog.api.client.ApiClient; import com.datadog.api.client.ApiException; import com.datadog.api.client.v1.api.MonitorsApi; import com.datadog.api.client.v1.model.Monitor; import com.datadog.api.client.v1.model.MonitorType; import java.util.Arrays; public class MonitorCreatedExample { public static void main(String[] args) { ApiClient defaultClient = ApiClient.getDefaultApiClient(); MonitorsApi apiInstance = new MonitorsApi(defaultClient); Monitor body = new Monitor() .name("my-monitor") .type(MonitorType.LOG_ALERT) .query( """ logs("service:foo AND type:error").index("main").rollup("count").by("source").last("5m") > 2 """) .message("some message Notify: @hipchat-channel") .tags(Arrays.asList("test:example", "env:ci")) .priority(3L); try { Monitor result = apiInstance.createMonitor(body); System.out.println(result); } catch (ApiException e) { System.err.println("Exception when calling MonitorsApi#createMonitor"); System.err.println("Status code: " + e.getCode()); System.err.println("Reason: " + e.getResponseBody()); System.err.println("Response headers: " + e.getResponseHeaders()); e.printStackTrace(); } } } ``` -------------------------------- ### Automatic Cursor Pagination with PaginationIterable Source: https://context7.com/datadog/datadog-api-client-java/llms.txt This example demonstrates how to use `PaginationIterable` to automatically fetch all results from a paginated API endpoint, such as `LogsApi.listLogsWithPagination`. It simplifies iterating through large datasets without manual cursor management. ```APIDOC ## PaginationIterable — Automatic Cursor Pagination Many list APIs expose a `...WithPagination` variant returning a `PaginationIterable` that automatically fetches subsequent pages using cursor tokens. ```java import com.datadog.api.client.ApiClient; import com.datadog.api.client.v2.api.LogsApi; import com.datadog.api.client.v2.api.LogsApi.ListLogsOptionalParameters; import com.datadog.api.client.v2.model.Log; import com.datadog.api.client.v2.model.LogsListRequest; import com.datadog.api.client.v2.model.LogsQueryFilter; import com.datadog.api.client.v2.model.LogsListRequestPage; public class PaginationExample { public static void main(String[] args) { ApiClient defaultClient = ApiClient.getDefaultApiClient(); LogsApi apiInstance = new LogsApi(defaultClient); LogsListRequest body = new LogsListRequest() .filter( new LogsQueryFilter() .from("now-1h") .query("service:payment-service") .to("now")) .page(new LogsListRequestPage().limit(200)); try { // Automatically pages through all results for (Log log : apiInstance.listLogsWithPagination( new ListLogsOptionalParameters().body(body))) { System.out.println(log.getId() + ": " + log.getAttributes().getMessage()); } } catch (Exception e) { System.err.println("Error during pagination: " + e.getMessage()); e.printStackTrace(); } } } ``` ``` -------------------------------- ### Automatic Cursor Pagination with PaginationIterable Source: https://context7.com/datadog/datadog-api-client-java/llms.txt Use `...WithPagination` variants to automatically fetch subsequent pages of results using cursor tokens. This example iterates through logs. ```java import com.datadog.api.client.ApiClient; import com.datadog.api.client.v2.api.LogsApi; import com.datadog.api.client.v2.api.LogsApi.ListLogsOptionalParameters; import com.datadog.api.client.v2.model.Log; import com.datadog.api.client.v2.model.LogsListRequest; import com.datadog.api.client.v2.model.LogsQueryFilter; import com.datadog.api.client.v2.model.LogsListRequestPage; public class PaginationExample { public static void main(String[] args) { ApiClient defaultClient = ApiClient.getDefaultApiClient(); LogsApi apiInstance = new LogsApi(defaultClient); LogsListRequest body = new LogsListRequest() .filter( new LogsQueryFilter() .from("now-1h") .query("service:payment-service") .to("now")) .page(new LogsListRequestPage().limit(200)); try { // Automatically pages through all results for (Log log : apiInstance.listLogsWithPagination( new ListLogsOptionalParameters().body(body))) { System.out.println(log.getId() + ": " + log.getAttributes().getMessage()); } } catch (Exception e) { System.err.println("Error during pagination: " + e.getMessage()); e.printStackTrace(); } } } ``` -------------------------------- ### Error Handling with ApiException Source: https://context7.com/datadog/datadog-api-client-java/llms.txt This example shows how to catch and handle `ApiException` which is thrown for failed API calls. It demonstrates inspecting the HTTP status code and response body to provide specific error messages for common scenarios like bad requests or rate limiting. ```APIDOC ## ApiException — Error Handling `ApiException` carries the HTTP status code, response body, and response headers from failed API calls. ```java import com.datadog.api.client.ApiClient; import com.datadog.api.client.ApiException; import com.datadog.api.client.v2.api.MetricsApi; import com.datadog.api.client.v2.model.MetricPayload; import com.datadog.api.client.v2.model.MetricSeries; import com.datadog.api.client.v2.model.MetricPoint; import com.datadog.api.client.v2.model.MetricIntakeType; import java.time.OffsetDateTime; import java.util.Collections; public class ErrorHandlingExample { public static void main(String[] args) { ApiClient defaultClient = ApiClient.getDefaultApiClient(); MetricsApi apiInstance = new MetricsApi(defaultClient); MetricPayload body = new MetricPayload() .series(Collections.singletonList( new MetricSeries() .metric("my.metric") .type(MetricIntakeType.COUNT) .points(Collections.singletonList( new MetricPoint() .timestamp(OffsetDateTime.now().toInstant().getEpochSecond()) .value(1.0))))); try { apiInstance.submitMetrics(body); } catch (ApiException e) { int status = e.getCode(); if (status == 400) { System.err.println("Bad request - check payload: " + e.getResponseBody()); } else if (status == 403) { System.err.println("Forbidden - check API/App keys"); } else if (status == 429) { System.err.println("Rate limited - retry after: " + e.getResponseHeaders().get("x-ratelimit-reset")); } else { System.err.println("Unexpected error " + status + ": " + e.getResponseBody()); } e.printStackTrace(); } } } ``` ``` -------------------------------- ### v2 LogsApi — Aggregate Logs Source: https://context7.com/datadog/datadog-api-client-java/llms.txt Runs group-by and compute aggregations over log data. This example demonstrates counting logs by HTTP status code. ```java import com.datadog.api.client.ApiClient; import com.datadog.api.client.ApiException; import com.datadog.api.client.v2.api.LogsApi; import com.datadog.api.client.v2.model.*; import java.util.Arrays; import java.util.Collections; public class AggregateLogsExample { public static void main(String[] args) { ApiClient defaultClient = ApiClient.getDefaultApiClient(); LogsApi apiInstance = new LogsApi(defaultClient); LogsAggregateRequest body = new LogsAggregateRequest() .filter( new LogsQueryFilter() .from("now-1d") .indexes(Collections.singletonList("main")) .query("service:payment-service") .to("now")) .groupBy( Collections.singletonList( new LogsGroupBy() .facet("@http.status_code") .limit(10L) .sort(new LogsGroupByHistogram().aggregation(LogsAggregationFunction.COUNT)))) .compute( Collections.singletonList( new LogsCompute() .aggregation(LogsAggregationFunction.COUNT) .metric("@duration"))); try { LogsAggregateResponse result = apiInstance.aggregateLogs(body); System.out.println(result); } catch (ApiException e) { System.err.println("Status code: " + e.getCode()); System.err.println("Reason: " + e.getResponseBody()); e.printStackTrace(); } } } ``` -------------------------------- ### Configure Datadog API Client Server Source: https://github.com/datadog/datadog-api-client-java/blob/master/README.md Changes the Datadog API server endpoint, for example, to the EU instance, by setting server variables on the client. ```java HashMap serverVariables = new HashMap(); serverVariables.put("site", "datadoghq.eu"); defaultApiClient.setServerVariables(serverVariables); ``` -------------------------------- ### v2 RolesApi — Create a Role with Permissions Source: https://context7.com/datadog/datadog-api-client-java/llms.txt Creates a custom RBAC role and attaches permission IDs to it in a single request. Requires retrieving permission UUIDs beforehand, for example, using `apiInstance.listPermissions()`. The permission ID can be set via environment variable `DD_LOGS_READ_PERMISSION_ID`. ```java import com.datadog.api.client.ApiClient; import com.datadog.api.client.ApiException; import com.datadog.api.client.v2.api.RolesApi; import com.datadog.api.client.v2.model.*; import java.util.Arrays; public class CreateRoleExample { public static void main(String[] args) { ApiClient defaultClient = ApiClient.getDefaultApiClient(); RolesApi apiInstance = new RolesApi(defaultClient); // Retrieve permission UUIDs first via apiInstance.listPermissions() String logsReadPermissionId = System.getenv("DD_LOGS_READ_PERMISSION_ID"); RoleCreateRequest body = new RoleCreateRequest() .data( new RoleCreateData() .attributes(new RoleCreateAttributes().name("read-only-logs")) .relationships( new RoleRelationships() .permissions( new RelationshipToPermissions() .data( Arrays.asList( new RelationshipToPermissionData() .type(PermissionsType.PERMISSIONS) .id(logsReadPermissionId))))) .type(RolesType.ROLES)); try { RoleCreateResponse result = apiInstance.createRole(body); System.out.println("Role ID: " + result.getData().getId()); } catch (ApiException e) { System.err.println("Status code: " + e.getCode()); System.err.println("Reason: " + e.getResponseBody()); e.printStackTrace(); } } } ``` -------------------------------- ### Initialize and Configure ApiClient in Java Source: https://context7.com/datadog/datadog-api-client-java/llms.txt Set up the ApiClient with authentication, site targeting, retry logic, debug logging, compression settings, and unstable operation enablement. Create one ApiClient per thread. ```java import com.datadog.api.client.ApiClient; import java.util.HashMap; public class ClientSetupExample { public static void main(String[] args) { ApiClient client = ApiClient.getDefaultApiClient(); // Authenticate using API key and Application key HashMap secrets = new HashMap<>(); secrets.put("apiKeyAuth", System.getenv("DD_API_KEY")); secrets.put("appKeyAuth", System.getenv("DD_APP_KEY")); client.configureApiKeys(secrets); // Target the EU region HashMap serverVariables = new HashMap<>(); serverVariables.put("site", "datadoghq.eu"); client.setServerVariables(serverVariables); // Enable auto-retry on 429 and 5xx client.enableRetry(true); // Enable request/response debug logging client.setDebugging(true); // Disable GZIP compression client.setCompress(false); // Enable an unstable (beta) operation client.setUnstableOperationEnabled("v2.createIncident", true); } } ``` -------------------------------- ### ApiClient Initialization and Configuration Source: https://context7.com/datadog/datadog-api-client-java/llms.txt Initialize and configure the ApiClient for making API requests. This includes setting authentication credentials, targeting a specific Datadog region, enabling auto-retry, debug logging, and disabling GZIP compression. ```APIDOC ## ApiClient — Client Initialization and Configuration `ApiClient` is the central HTTP client. Create one per thread, configure credentials, site, and options before constructing any API instance. ```java import com.datadog.api.client.ApiClient; import java.util.HashMap; public class ClientSetupExample { public static void main(String[] args) { ApiClient client = ApiClient.getDefaultApiClient(); // Authenticate using API key and Application key HashMap secrets = new HashMap<>(); secrets.put("apiKeyAuth", System.getenv("DD_API_KEY")); secrets.put("appKeyAuth", System.getenv("DD_APP_KEY")); client.configureApiKeys(secrets); // Target the EU region HashMap serverVariables = new HashMap<>(); serverVariables.put("site", "datadoghq.eu"); client.setServerVariables(serverVariables); // Enable auto-retry on 429 and 5xx client.enableRetry(true); // Enable request/response debug logging client.setDebugging(true); // Disable GZIP compression client.setCompress(false); // Enable an unstable (beta) operation client.setUnstableOperationEnabled("v2.createIncident", true); } } ``` ``` -------------------------------- ### Error Handling with ApiException Source: https://context7.com/datadog/datadog-api-client-java/llms.txt Catch `ApiException` to access HTTP status codes, response bodies, and headers from failed API calls. This example handles common error statuses for metric submission. ```java import com.datadog.api.client.ApiClient; import com.datadog.api.client.ApiException; import com.datadog.api.client.v2.api.MetricsApi; import com.datadog.api.client.v2.model.MetricPayload; import com.datadog.api.client.v2.model.MetricSeries; import com.datadog.api.client.v2.model.MetricPoint; import com.datadog.api.client.v2.model.MetricIntakeType; import java.time.OffsetDateTime; import java.util.Collections; public class ErrorHandlingExample { public static void main(String[] args) { ApiClient defaultClient = ApiClient.getDefaultApiClient(); MetricsApi apiInstance = new MetricsApi(defaultClient); MetricPayload body = new MetricPayload() .series(Collections.singletonList( new MetricSeries() .metric("my.metric") .type(MetricIntakeType.COUNT) .points(Collections.singletonList( new MetricPoint() .timestamp(OffsetDateTime.now().toInstant().getEpochSecond()) .value(1.0)))))); try { apiInstance.submitMetrics(body); } catch (ApiException e) { int status = e.getCode(); if (status == 400) { System.err.println("Bad request - check payload: " + e.getResponseBody()); } else if (status == 403) { System.err.println("Forbidden - check API/App keys"); } else if (status == 429) { System.err.println("Rate limited - retry after: " + e.getResponseHeaders().get("x-ratelimit-reset")); } else { System.err.println("Unexpected error " + status + ": " + e.getResponseBody()); } e.printStackTrace(); } } } ``` -------------------------------- ### Deploy Datadog API Client (Maven) Source: https://github.com/datadog/datadog-api-client-java/blob/master/README.md Deploys the Datadog API client library to a remote Maven repository. Requires repository configuration. ```shell mvn clean deploy ``` -------------------------------- ### Create a Log Alert Monitor (v1) Source: https://context7.com/datadog/datadog-api-client-java/llms.txt Use this snippet to create a log alert monitor using the v1 MonitorsApi. Ensure the necessary imports are included and handle potential API exceptions. ```java import com.datadog.api.client.ApiClient; import com.datadog.api.client.ApiException; import com.datadog.api.client.v1.api.MonitorsApi; import com.datadog.api.client.v1.model.Monitor; import com.datadog.api.client.v1.model.MonitorType; import java.util.Arrays; public class CreateMonitorExample { public static void main(String[] args) { ApiClient defaultClient = ApiClient.getDefaultApiClient(); MonitorsApi apiInstance = new MonitorsApi(defaultClient); Monitor body = new Monitor() .name("High error rate on payment service") .type(MonitorType.LOG_ALERT) .query( "logs(\"service:payment AND status:error\").index(\"main\")" + ".rollup(\"count\").by(\"env\").last(\"5m\") > 10") .message("Payment service error rate exceeded threshold. Notify: @pagerduty-payments") .tags(Arrays.asList("service:payment", "env:prod", "team:backend")) .priority(2L); try { Monitor result = apiInstance.createMonitor(body); System.out.println("Created monitor ID: " + result.getId()); } catch (ApiException e) { System.err.println("Exception when calling MonitorsApi#createMonitor"); System.err.println("Status code: " + e.getCode()); System.err.println("Reason: " + e.getResponseBody()); e.printStackTrace(); } } } ``` -------------------------------- ### Create a User Source: https://context7.com/datadog/datadog-api-client-java/llms.txt `UsersApi.createUser` provisions a new Datadog user account with a name and email address. ```APIDOC ## v2 UsersApi — Create a User `UsersApi.createUser` provisions a new Datadog user account with a name and email address. ### Description Provisions a new Datadog user account. ### Method POST ### Endpoint `/api/v2/users` ### Request Body - **data** (UserCreateRequest) - Required - The user to create. - **type** (UsersType) - Required - Type of the user. - **attributes** (UserCreateAttributes) - Required - Attributes of the user. - **name** (string) - Required - Name of the user. - **email** (string) - Required - Email of the user. ### Request Example ```json { "data": { "type": "users", "attributes": { "name": "Jane Smith", "email": "jane.smith@company.com" } } } ``` ### Response #### Success Response (201 Created) - **data** (UserResponse) - The created user. - **id** (string) - The user's ID. - **attributes** (UserAttributes) - Attributes of the user. - **email** (string) - Email of the user. #### Response Example ```json { "data": { "id": "a1b2c3d4-e5f6-7890-1234-567890abcdef", "attributes": { "name": "Jane Smith", "email": "jane.smith@company.com", "created_at": "2023-01-01T12:00:00Z", "modified_at": "2023-01-01T12:00:00Z" }, "type": "users" } } ``` ``` -------------------------------- ### v1 MonitorsApi — Create a Monitor Source: https://context7.com/datadog/datadog-api-client-java/llms.txt Use `createMonitor` to define threshold-based log, metric, or APM monitors. ```APIDOC ## v1 MonitorsApi — Create a Monitor `MonitorsApi` (v1) manages alert monitors. Use `createMonitor` to define threshold-based log, metric, or APM monitors. ### Method POST ### Endpoint /api/v1/monitor ### Request Body - **name** (string) - Required - The name of the monitor. - **type** (MonitorType) - Required - The type of monitor. - **query** (string) - Required - The monitor query string. - **message** (string) - Required - The monitor message. - **tags** (list of strings) - Optional - A list of tags to associate with the monitor. - **priority** (long) - Optional - The monitor priority. ### Request Example ```java Monitor body = new Monitor() .name("High error rate on payment service") .type(MonitorType.LOG_ALERT) .query("logs(\"service:payment AND status:error\").index(\"main\")" + ".rollup(\"count\").by(\"env\").last(\"5m\") > 10") .message("Payment service error rate exceeded threshold. Notify: @pagerduty-payments") .tags(Arrays.asList("service:payment", "env:prod", "team:backend")) .priority(2L); ``` ### Response #### Success Response (200) - **id** (string) - The ID of the created monitor. ### Response Example ```json { "id": "12345" } ``` ``` -------------------------------- ### Create a Detection Rule Source: https://context7.com/datadog/datadog-api-client-java/llms.txt `SecurityMonitoringApi.createSecurityMonitoringRule` defines log-based or cloud-configuration threat detection rules with thresholds, evaluation windows, and severity cases. ```APIDOC ## v2 SecurityMonitoringApi — Create a Detection Rule `SecurityMonitoringApi.createSecurityMonitoringRule` defines log-based or cloud-configuration threat detection rules with thresholds, evaluation windows, and severity cases. ```java import com.datadog.api.client.ApiClient; import com.datadog.api.client.ApiException; import com.datadog.api.client.v2.api.SecurityMonitoringApi; import com.datadog.api.client.v2.model.*; import java.util.Collections; public class CreateSecurityRuleExample { public static void main(String[] args) { ApiClient defaultClient = ApiClient.getDefaultApiClient(); SecurityMonitoringApi apiInstance = new SecurityMonitoringApi(defaultClient); SecurityMonitoringRuleCreatePayload body = new SecurityMonitoringRuleCreatePayload( new SecurityMonitoringStandardRuleCreatePayload() .name("Brute Force Login Attempt") .queries( Collections.singletonList( new SecurityMonitoringStandardRuleQuery() .query("@evt.name:failed_login @usr.id:*") .aggregation(SecurityMonitoringRuleQueryAggregation.COUNT) .groupByFields(Collections.singletonList("@usr.id")) .metric(""))) .cases( Collections.singletonList( new SecurityMonitoringRuleCaseCreate() .name("High volume login failures") .status(SecurityMonitoringRuleSeverity.HIGH) .condition("a > 20"))) .options( new SecurityMonitoringRuleOptions() .evaluationWindow(SecurityMonitoringRuleEvaluationWindow.FIVE_MINUTES) .keepAlive(SecurityMonitoringRuleKeepAlive.TEN_MINUTES) .maxSignalDuration(SecurityMonitoringRuleMaxSignalDuration.ONE_HOUR)) .message("Brute force detected for user {{@usr.id}}. Notify: @security-team") .tags(Collections.singletonList("security:authentication")) .isEnabled(true) .type(SecurityMonitoringRuleTypeCreate.LOG_DETECTION)); try { SecurityMonitoringRuleResponse result = apiInstance.createSecurityMonitoringRule(body); System.out.println("Rule ID: " + result.getId()); } catch (ApiException e) { System.err.println("Status code: " + e.getCode()); System.err.println("Reason: " + e.getResponseBody()); e.printStackTrace(); } } } ``` ``` -------------------------------- ### Create Security Monitoring Detection Rule with Java Source: https://context7.com/datadog/datadog-api-client-java/llms.txt Define log-based or cloud-configuration threat detection rules. This includes setting up queries, cases, options for evaluation windows, and enabling the rule. ```java import com.datadog.api.client.ApiClient; import com.datadog.api.client.ApiException; import com.datadog.api.client.v2.api.SecurityMonitoringApi; import com.datadog.api.client.v2.model.*; import java.util.Collections; public class CreateSecurityRuleExample { public static void main(String[] args) { ApiClient defaultClient = ApiClient.getDefaultApiClient(); SecurityMonitoringApi apiInstance = new SecurityMonitoringApi(defaultClient); SecurityMonitoringRuleCreatePayload body = new SecurityMonitoringRuleCreatePayload( new SecurityMonitoringStandardRuleCreatePayload() .name("Brute Force Login Attempt") .queries( Collections.singletonList( new SecurityMonitoringStandardRuleQuery() .query("@evt.name:failed_login @usr.id:*") .aggregation(SecurityMonitoringRuleQueryAggregation.COUNT) .groupByFields(Collections.singletonList("@usr.id")) .metric(""))) .cases( Collections.singletonList( new SecurityMonitoringRuleCaseCreate() .name("High volume login failures") .status(SecurityMonitoringRuleSeverity.HIGH) .condition("a > 20"))) .options( new SecurityMonitoringRuleOptions() .evaluationWindow(SecurityMonitoringRuleEvaluationWindow.FIVE_MINUTES) .keepAlive(SecurityMonitoringRuleKeepAlive.TEN_MINUTES) .maxSignalDuration(SecurityMonitoringRuleMaxSignalDuration.ONE_HOUR)) .message("Brute force detected for user {{@usr.id}}. Notify: @security-team") .tags(Collections.singletonList("security:authentication")) .isEnabled(true) .type(SecurityMonitoringRuleTypeCreate.LOG_DETECTION)); try { SecurityMonitoringRuleResponse result = apiInstance.createSecurityMonitoringRule(body); System.out.println("Rule ID: " + result.getId()); } catch (ApiException e) { System.err.println("Status code: " + e.getCode()); System.err.println("Reason: " + e.getResponseBody()); e.printStackTrace(); } } } ``` -------------------------------- ### v2 UsersApi — Create a User Source: https://context7.com/datadog/datadog-api-client-java/llms.txt Provisions a new Datadog user account with a name and email address. Ensure the Datadog API client is initialized. ```java import com.datadog.api.client.ApiClient; import com.datadog.api.client.ApiException; import com.datadog.api.client.v2.api.UsersApi; import com.datadog.api.client.v2.model.*; public class CreateUserExample { public static void main(String[] args) { ApiClient defaultClient = ApiClient.getDefaultApiClient(); UsersApi apiInstance = new UsersApi(defaultClient); UserCreateRequest body = new UserCreateRequest() .data( new UserCreateData() .type(UsersType.USERS) .attributes( new UserCreateAttributes() .name("Jane Smith") .email("jane.smith@company.com"))); try { UserResponse result = apiInstance.createUser(body); System.out.println("User ID: " + result.getData().getId()); System.out.println("Email: " + result.getData().getAttributes().getEmail()); } catch (ApiException e) { System.err.println("Status code: " + e.getCode()); System.err.println("Reason: " + e.getResponseBody()); e.printStackTrace(); } } } ``` -------------------------------- ### Execute a Workflow Source: https://context7.com/datadog/datadog-api-client-java/llms.txt `WorkflowAutomationApi.createWorkflowInstance` triggers a Datadog Workflow Automation workflow by its ID, passing input parameters as a JSON payload. ```APIDOC ## v2 WorkflowAutomationApi — Execute a Workflow `WorkflowAutomationApi.createWorkflowInstance` triggers a Datadog Workflow Automation workflow by its ID, passing input parameters as a JSON payload. ```java import com.datadog.api.client.ApiClient; import com.datadog.api.client.ApiException; import com.datadog.api.client.v2.api.WorkflowAutomationApi; import com.datadog.api.client.v2.model.*; import java.util.Map; public class TriggerWorkflowExample { public static void main(String[] args) { ApiClient defaultClient = ApiClient.getDefaultApiClient(); WorkflowAutomationApi apiInstance = new WorkflowAutomationApi(defaultClient); String workflowId = "ccf73164-1998-4785-a7a3-8d06c7e5f558"; // from Datadog UI WorkflowInstanceCreateRequest body = new WorkflowInstanceCreateRequest() .meta( new WorkflowInstanceCreateMeta() .payload( Map.ofEntries( Map.entry("service", "payment-service"), Map.entry("action", "rollback"), Map.entry("target_version", "v2.0.9")))); try { WorkflowInstanceCreateResponse result = apiInstance.createWorkflowInstance(workflowId, body); System.out.println("Workflow instance ID: " + result.getData().getId()); } catch (ApiException e) { System.err.println("Status code: " + e.getCode()); System.err.println("Reason: " + e.getResponseBody()); e.printStackTrace(); } } } ``` ``` -------------------------------- ### Record API Responses for Integration Tests Source: https://github.com/datadog/datadog-api-client-java/blob/master/DEVELOPMENT.md Run integration tests with RECORD=true to capture API responses in cassettes for later use. This is crucial for ensuring test consistency and reducing reliance on live API calls. ```bash RECORD=true mvn test ``` -------------------------------- ### v2 MonitorsApi — Create a Monitor Configuration Policy Source: https://context7.com/datadog/datadog-api-client-java/llms.txt Adds configuration policies that enforce tag requirements across all monitors in an organization. ```APIDOC ## v2 MonitorsApi — Create a Monitor Configuration Policy `MonitorsApi` (v2) adds configuration policies that enforce tag requirements across all monitors in an organization. ### Method POST ### Endpoint /api/v2/monitor/config/policy ### Request Body - **data** (MonitorConfigPolicyCreateRequestData) - Required - The monitor configuration policy request data. - **attributes** (MonitorConfigPolicyAttributeCreateRequest) - Required - The attributes of the monitor configuration policy. - **policyType** (MonitorConfigPolicyType) - Required - The type of policy. - **policy** (MonitorConfigPolicyPolicyCreateRequest) - Required - The policy details. - **tagKey** (string) - Required - The tag key to enforce. - **tagKeyRequired** (boolean) - Required - Whether the tag key is required. - **validTagValues** (list of strings) - Optional - A list of valid tag values for the tag key. - **type** (MonitorConfigPolicyResourceType) - Required - The resource type. ### Request Example ```java MonitorConfigPolicyCreateRequest body = new MonitorConfigPolicyCreateRequest() .data( new MonitorConfigPolicyCreateData() .attributes( new MonitorConfigPolicyAttributeCreateRequest() .policyType(MonitorConfigPolicyType.TAG) .policy( new MonitorConfigPolicyPolicyCreateRequest( new MonitorConfigPolicyTagPolicyCreateRequest() .tagKey("env") .tagKeyRequired(true) .validTagValues(Arrays.asList("prod", "staging", "dev"))))) .type(MonitorConfigPolicyResourceType.MONITOR_CONFIG_POLICY)); ``` ### Response #### Success Response (200) - **data** (MonitorConfigPolicyResponseData) - The monitor configuration policy response data. - **id** (string) - The ID of the policy. ### Response Example ```json { "data": { "id": "policy-id-123" } } ``` ``` -------------------------------- ### Generate JAR Package (Maven) Source: https://github.com/datadog/datadog-api-client-java/blob/master/README.md Generates the JAR file for the Datadog API client library using Maven. ```shell mvn clean package ``` -------------------------------- ### Create a Datadog Synthetics Network Path Test Source: https://context7.com/datadog/datadog-api-client-java/llms.txt Use `SyntheticsApi.createSyntheticsNetworkTest` to create network performance monitoring tests. Configure test name, message, assertions, target host, port, and locations. Ensure the API client is initialized. ```java import com.datadog.api.client.ApiClient; import com.datadog.api.client.ApiException; import com.datadog.api.client.v2.api.SyntheticsApi; import com.datadog.api.client.v2.model.*; import java.util.Arrays; import java.util.Collections; public class CreateSyntheticsNetworkTestExample { public static void main(String[] args) { ApiClient defaultClient = ApiClient.getDefaultApiClient(); SyntheticsApi apiInstance = new SyntheticsApi(defaultClient); SyntheticsNetworkTestEditRequest body = new SyntheticsNetworkTestEditRequest() .data( new SyntheticsNetworkTestEdit() .attributes( new SyntheticsNetworkTest() .name("Check latency to payment gateway") .message("Network Path latency exceeded SLO. Notify: @ops-team") .config( new SyntheticsNetworkTestConfig() .assertions( Collections.singletonList( new SyntheticsNetworkAssertion( new SyntheticsNetworkAssertionLatency() .operator(SyntheticsNetworkAssertionOperator.LESS_THAN) .property(SyntheticsNetworkAssertionProperty.AVG) .target(200.0) .type(SyntheticsNetworkAssertionLatencyType.LATENCY)))) .request( new SyntheticsNetworkTestRequest() .host("payment-gateway.internal") .port(443L) .tcpMethod(SyntheticsNetworkTestRequestTCPMethod.PREFER_SACK))) .locations(Arrays.asList("aws:us-east-1", "aws:eu-west-1")) .options(new SyntheticsTestOptions().tickEvery(300L)) .status(SyntheticsTestPauseStatus.LIVE) .subtype(SyntheticsNetworkTestSubType.TCP) .tags(Collections.singletonList("team:ops")) .type(SyntheticsNetworkTestType.NETWORK)) .type(SyntheticsNetworkTestType.NETWORK)); try { SyntheticsNetworkTestResponse result = apiInstance.createSyntheticsNetworkTest(body); System.out.println("Test public ID: " + result.getData().getId()); } catch (ApiException e) { System.err.println("Status code: " + e.getCode()); System.err.println("Reason: " + e.getResponseBody()); e.printStackTrace(); } } } ``` -------------------------------- ### List Monitors Asynchronously Source: https://github.com/datadog/datadog-api-client-java/blob/master/README.md Demonstrates how to asynchronously list Datadog monitors using the Java API client. Returns a CompletableFuture. ```java import com.datadog.api.client.ApiClient; import com.datadog.api.client.v1.api.MonitorsApi; public class ListMonitorsAsyncExample { public static void main(String[] args) { ApiClient defaultClient = ApiClient.getDefaultApiClient(); MonitorsApi apiInstance = new MonitorsApi(defaultClient); apiInstance.listMonitorsAsync().thenApply(monitors -> { System.out.println(monitors); return null; }).exceptionally(error -> { System.out.println(error); return null; }); } } ``` -------------------------------- ### Asynchronous API Calls Source: https://context7.com/datadog/datadog-api-client-java/llms.txt Demonstrates how to make asynchronous API calls using the `Async` variants of API methods, which return `CompletableFuture`. ```APIDOC ## Asynchronous API calls Every synchronous API method has an `Async` variant that returns `CompletableFuture`. ```java import com.datadog.api.client.ApiClient; import com.datadog.api.client.v1.api.MonitorsApi; public class AsyncExample { public static void main(String[] args) { ApiClient defaultClient = ApiClient.getDefaultApiClient(); MonitorsApi apiInstance = new MonitorsApi(defaultClient); apiInstance .listMonitorsAsync() .thenApply(monitors -> { System.out.println("Monitor count: " + monitors.size()); return null; }) .exceptionally(error -> { System.err.println("Error: " + error.getMessage()); return null; }); } } ``` ``` -------------------------------- ### Execute a Workflow Source: https://context7.com/datadog/datadog-api-client-java/llms.txt Use `createWorkflowInstance` to trigger a Datadog Workflow Automation workflow. Provide the workflow ID and input parameters as a JSON payload. ```java import com.datadog.api.client.ApiClient; import com.datadog.api.client.ApiException; import com.datadog.api.client.v2.api.WorkflowAutomationApi; import com.datadog.api.client.v2.model.*; import java.util.Map; public class TriggerWorkflowExample { public static void main(String[] args) { ApiClient defaultClient = ApiClient.getDefaultApiClient(); WorkflowAutomationApi apiInstance = new WorkflowAutomationApi(defaultClient); String workflowId = "ccf73164-1998-4785-a7a3-8d06c7e5f558"; // from Datadog UI WorkflowInstanceCreateRequest body = new WorkflowInstanceCreateRequest() .meta( new WorkflowInstanceCreateMeta() .payload( Map.ofEntries( Map.entry("service", "payment-service"), Map.entry("action", "rollback"), Map.entry("target_version", "v2.0.9")))); try { WorkflowInstanceCreateResponse result = apiInstance.createWorkflowInstance(workflowId, body); System.out.println("Workflow instance ID: " + result.getData().getId()); } catch (ApiException e) { System.err.println("Status code: " + e.getCode()); System.err.println("Reason: " + e.getResponseBody()); e.printStackTrace(); } } } ``` -------------------------------- ### Send DORA Deployment Event Source: https://context7.com/datadog/datadog-api-client-java/llms.txt Use `createDORADeployment` to send deployment data for DORA metrics. Ensure timestamps are in nanoseconds. ```java import com.datadog.api.client.ApiClient; import com.datadog.api.client.ApiException; import com.datadog.api.client.v2.api.DoraMetricsApi; import com.datadog.api.client.v2.model.*; public class CreateDORADeploymentExample { public static void main(String[] args) { ApiClient defaultClient = ApiClient.getDefaultApiClient(); DoraMetricsApi apiInstance = new DoraMetricsApi(defaultClient); long now = System.currentTimeMillis() * 1_000_000L; // nanoseconds DORADeploymentRequest body = new DORADeploymentRequest() .data( new DORADeploymentRequestData() .attributes( new DORADeploymentRequestAttributes() .service("payment-service") .version("v2.1.0") .startedAt(now - 120_000_000_000L) // 2 minutes ago .finishedAt(now) .git( new DORAGitInfo() .commitSha("a3f9d2b1c8e4f6071234abcde98765fedcba0123") .repositoryUrl( "https://github.com/company/payment-service")))); try { DORADeploymentResponse result = apiInstance.createDORADeployment(body); System.out.println("DORA event ID: " + result.getData().getId()); } catch (ApiException e) { System.err.println("Status code: " + e.getCode()); System.err.println("Reason: " + e.getResponseBody()); e.printStackTrace(); } } } ``` -------------------------------- ### Run Integration Tests Without Recording Cassettes Source: https://github.com/datadog/datadog-api-client-java/blob/master/DEVELOPMENT.md Execute integration tests against the live API without recording new cassettes by setting RECORD=none. This is useful for testing against the most recent API behavior. ```bash RECORD=none mvn test ``` -------------------------------- ### Create a Datadog APM Retention Filter Source: https://context7.com/datadog/datadog-api-client-java/llms.txt Use `ApmRetentionFiltersApi.createApmRetentionFilter` to define sampling rules for APM traces. Configure filter name, enabled status, query, filter type, and retention rate. Ensure the API client is initialized. ```java import com.datadog.api.client.ApiClient; import com.datadog.api.client.ApiException; import com.datadog.api.client.v2.api.ApmRetentionFiltersApi; import com.datadog.api.client.v2.model.*; public class CreateRetentionFilterExample { public static void main(String[] args) { ApiClient defaultClient = ApiClient.getDefaultApiClient(); ApmRetentionFiltersApi apiInstance = new ApmRetentionFiltersApi(defaultClient); RetentionFilterCreateRequest body = new RetentionFilterCreateRequest() .data( new RetentionFilterCreateData() .attributes( new RetentionFilterCreateAttributes() .name("Retain errors for payment-service") .enabled(true) .filter( new SpansFilterCreate() .query("service:payment-service status:error")) .filterType(RetentionFilterType.SPANS_SAMPLING_PROCESSOR) .rate(1.0)) // 100% of matching spans .type(ApmRetentionFilterType.apm_retention_filter)); try { RetentionFilterCreateResponse result = apiInstance.createApmRetentionFilter(body); System.out.println("Filter ID: " + result.getData().getId()); } catch (ApiException e) { System.err.println("Status code: " + e.getCode()); System.err.println("Reason: " + e.getResponseBody()); e.printStackTrace(); } } } ``` -------------------------------- ### Create a Team Source: https://context7.com/datadog/datadog-api-client-java/llms.txt `TeamsApi.createTeam` creates an organizational team used for ownership assignment and routing alerts. ```APIDOC ## v2 TeamsApi — Create a Team `TeamsApi.createTeam` creates an organizational team used for ownership assignment and routing alerts. ### Description Creates an organizational team. ### Method POST ### Endpoint `/api/v2/teams` ### Request Body - **data** (TeamCreateRequest) - Required - The team to create. - **type** (TeamType) - Required - Type of the team. - **attributes** (TeamCreateAttributes) - Required - Attributes of the team. - **handle** (string) - Required - Team's handle. - **name** (string) - Required - Team's name. - **description** (string) - Optional - Team's description. - **relationships** (TeamCreateRelationships) - Optional - Relationships of the team. - **users** (RelationshipToUsers) - Optional - Users to associate with the team. ### Request Example ```json { "data": { "type": "team", "attributes": { "handle": "backend-engineering", "name": "Backend Engineering", "description": "Owns payment, order, and inventory services" }, "relationships": { "users": {} } } } ``` ### Response #### Success Response (201 Created) - **data** (TeamResponse) - The created team. - **id** (string) - The team's ID. #### Response Example ```json { "data": { "id": "a1b2c3d4-e5f6-7890-1234-567890abcdef", "attributes": { "handle": "backend-engineering", "name": "Backend Engineering", "description": "Owns payment, order, and inventory services", "created_at": "2023-01-01T12:00:00Z", "modified_at": "2023-01-01T12:00:00Z" }, "type": "team" } } ``` ```