### Full Datadog API Client Application Example Source: https://github.com/datadog/datadog-api-client-typescript/blob/master/_autodocs/examples.md A comprehensive example showing the setup, authentication, monitor creation, listing, and cleanup process. It includes error handling and basic logging. ```typescript import { client, v1 } from '@datadog/datadog-api-client'; async function main() { try { // Setup const configuration = client.createConfiguration({ debug: process.env.DEBUG === 'true', enableRetry: true, maxRetries: 3 }); // Verify credentials const authApi = new v1.AuthenticationApi(configuration); const valid = await authApi.validate(); if (!valid.valid) { console.error('Invalid credentials'); process.exit(1); } console.log('✓ Authenticated'); // Create monitor const monitorsApi = new v1.MonitorsApi(configuration); const monitor = await monitorsApi.createMonitor({ body: { name: 'Application CPU Alert', type: v1.MonitorType.METRIC_ALERT, query: 'avg:system.cpu{service:myapp} by {host} > 0.8', message: 'CPU is high on {{host.name}} @pagerduty', tags: ['app:myapp', 'env:prod'], priority: 2, options: { thresholds: { critical: 0.8, warning: 0.6 }, evaluationDelay: 60, noDataTimeframe: 10 } } }); console.log(`✓ Created monitor ID ${monitor.id}`); // List all monitors const all = await monitorsApi.listMonitors(); console.log(`✓ Found ${all.length} total monitors`); // Cleanup await monitorsApi.deleteMonitor({ monitorId: monitor.id! }); console.log(`✓ Deleted monitor`); } catch (error) { if (error instanceof client.ApiException) { console.error(`API Error ${error.code}:`, error.body); } else { console.error('Error:', error); } process.exit(1); } } main(); ``` -------------------------------- ### Complete Configuration Example Source: https://github.com/datadog/datadog-api-client-typescript/blob/master/_autodocs/configuration-auth.md A comprehensive example demonstrating how to configure authentication, server selection, HTTP transport options, retry policies, and debugging. It also shows how to change server variables and use the configuration with an API instance. ```typescript import { client, v1 } from '@datadog/datadog-api-client'; const configuration = client.createConfiguration({ // Authentication authMethods: { apiKeyAuth: 'my_api_key', appKeyAuth: 'my_app_key' }, // Server selection serverIndex: 0, // HTTP transport httpConfig: { compress: true, signal: abortSignal }, // Retry policy enableRetry: true, maxRetries: 5, backoffBase: 2, backoffMultiplier: 2, // Debugging debug: true }); // Change region after creation configuration.setServerVariables({ site: 'datadoghq.eu' }); // Use with API const monitorsApi = new v1.MonitorsApi(configuration); const monitors = await monitorsApi.listMonitors(); ``` -------------------------------- ### HTTP Configuration - Example: Disable Compression Source: https://github.com/datadog/datadog-api-client-typescript/blob/master/_autodocs/configuration-auth.md Example demonstrating how to disable GZIP compression. ```APIDOC ### Example: Disable Compression ```typescript const configuration = client.createConfiguration({ httpConfig: { compress: false } }); ``` ``` -------------------------------- ### Server Configuration - Custom Server Source: https://github.com/datadog/datadog-api-client-typescript/blob/master/_autodocs/configuration-auth.md Example of how to configure a custom server. ```APIDOC ### Custom Server ```typescript const customServer = new client.BaseServerConfiguration( 'https://custom.example.com', { subdomain: 'api' } ); const configuration = client.createConfiguration({ baseServer: customServer }); ``` ``` -------------------------------- ### Install Datadog API Client using NPM or Yarn Source: https://github.com/datadog/datadog-api-client-typescript/blob/master/README.md Install the Datadog API client package for Node.js using either NPM or Yarn. ```sh # NPM npm install @datadog/datadog-api-client # Yarn yarn add @datadog/datadog-api-client ``` -------------------------------- ### Custom Server Configuration Example Source: https://github.com/datadog/datadog-api-client-typescript/blob/master/_autodocs/configuration-auth.md Demonstrates how to configure a custom server for the Datadog API client using BaseServerConfiguration. ```typescript const customServer = new client.BaseServerConfiguration( 'https://custom.example.com', { subdomain: 'api' } ); const configuration = client.createConfiguration({ baseServer: customServer }); ``` -------------------------------- ### HTTP Configuration - Example: Request Cancellation Source: https://github.com/datadog/datadog-api-client-typescript/blob/master/_autodocs/configuration-auth.md Example demonstrating how to cancel an API request using AbortSignal. ```APIDOC ### Example: Request Cancellation ```typescript const controller = new AbortController(); const configuration = client.createConfiguration({ httpConfig: { signal: controller.signal } }); const apiInstance = new v1.MonitorsApi(configuration); const promise = apiInstance.listMonitors(); // Cancel request controller.abort(); ``` ``` -------------------------------- ### Get a Monitor using Datadog API Client Source: https://github.com/datadog/datadog-api-client-typescript/blob/master/README.md Example of how to fetch a specific monitor by its ID using the Datadog API client. Ensure you have the necessary imports and configuration. ```typescript import { client, v1 } from '@datadog/datadog-api-client'; const configuration = client.createConfiguration(); const apiInstance = new v1.MonitorsApi(configuration); let params:v1.MonitorsApiGetMonitorRequest = { // number | The ID of the monitor monitorId: 1, }; apiInstance.getMonitor(params).then((data: v1.Monitor) => { console.log('API called successfully. Returned data: ' + data); }).catch((error:any) => console.error(error)); ``` -------------------------------- ### Example: Validate API Key with Explicit Configuration Source: https://github.com/datadog/datadog-api-client-typescript/blob/master/_autodocs/api-reference/authentication-api.md Demonstrates how to validate an API key using the AuthenticationApi, providing explicit configuration with an API key. ```typescript import { client, v1 } from '@datadog/datadog-api-client'; const configuration = client.createConfiguration({ authMethods: { apiKeyAuth: 'your_api_key' } }); const authApi = new v1.AuthenticationApi(configuration); try { const response = await authApi.validate(); if (response.valid) { console.log('API key is valid'); } else { console.log('API key is invalid'); } } catch (error) { if (error instanceof client.ApiException) { if (error.code === 403) { console.error('Authentication failed: Invalid API key'); } else if (error.code === 429) { console.error('Rate limited'); } } } ``` -------------------------------- ### Example: Validate API Key using Environment Variables Source: https://github.com/datadog/datadog-api-client-typescript/blob/master/_autodocs/api-reference/authentication-api.md Shows how to validate an API key by leveraging environment variables (DD_API_KEY) for configuration. ```typescript import { client, v1 } from '@datadog/datadog-api-client'; // Automatically uses DD_API_KEY from environment const configuration = client.createConfiguration(); const authApi = new v1.AuthenticationApi(configuration); const response = await authApi.validate(); console.log('Valid:', response.valid); ``` -------------------------------- ### Example: Disable Compression Source: https://github.com/datadog/datadog-api-client-typescript/blob/master/_autodocs/http-transport.md Demonstrates how to disable GZIP compression for all HTTP requests by setting `compress` to `false` in the `httpConfig`. ```typescript import { client } from '@datadog/datadog-api-client'; const configuration = client.createConfiguration({ httpConfig: { compress: false } }); ``` -------------------------------- ### Request Construction Example Source: https://github.com/datadog/datadog-api-client-typescript/blob/master/_autodocs/http-transport.md Builds a RequestContext for an API method, setting headers and query parameters. ```typescript const requestContext = configuration .getServer("v1.MonitorsApi.getMonitor") .makeRequestContext("/api/v1/monitor/{monitor_id}", HttpMethod.GET); requestContext.setHeaderParam("Accept", "application/json"); requestContext.setQueryParam("with_downtimes", "true"); applySecurityAuthentication(configuration, requestContext, [...]); ``` -------------------------------- ### Unstable Operations Source: https://github.com/datadog/datadog-api-client-typescript/blob/master/_autodocs/configuration-auth.md Instructions on how to enable and examples of unstable (preview) operations. ```APIDOC ## Unstable Operations Some operations are in preview state and may change. Enable them explicitly: ```typescript const configuration = client.createConfiguration(); configuration.unstableOperations['v2.createFleetDeployment'] = true; ``` Example unstable v2 operations: - Fleet management endpoints (`createFleetDeployment`, `listFleetAgents`, etc.) - LLM observability endpoints (`createLLMObsDataset`, `listLLMObsSpans`, etc.) - Annotation endpoints (`createAnnotation`, `listAnnotations`, etc.) - Custom OpenAPI endpoints (`createOpenAPI`, `updateOpenAPI`, etc.) ``` -------------------------------- ### Configure Proxy for API Requests Source: https://github.com/datadog/datadog-api-client-typescript/blob/master/README.md Implement a custom `HttpLibrary` to route requests through a proxy. This example uses `https-proxy-agent` and `node-fetch` to configure the proxy settings. ```typescript import pako from "pako"; import bufferFrom from "buffer-from"; import fetch from "node-fetch"; import { HttpsProxyAgent } from "https-proxy-agent"; import { v1, client } from "@datadog/datadog-api-client"; const proxyAgent = new HttpsProxyAgent('http://127.0.0.11:3128'); class HttpLibraryWithProxy implements client.HttpLibrary { public debug = false; public send(request: client.RequestContext): Promise { const method = request.getHttpMethod().toString(); let body = request.getBody(); let compress = request.getHttpConfig().compress; if (compress === undefined) { compress = true; } const headers = request.getHeaders(); if (typeof body === "string") { if (headers["Content-Encoding"] === "gzip") { body = bufferFrom(pako.gzip(body).buffer); } else if (headers["Content-Encoding"] === "deflate") { body = bufferFrom(pako.deflate(body).buffer); } } const resultPromise = fetch(request.getUrl(), { method: method, body: body as any, headers: headers, signal: request.getHttpConfig().signal, compress: compress, agent: proxyAgent, }).then((resp: any) => { const headers: { [name: string]: string } = {}; resp.headers.forEach((value: string, name: string) => { headers[name] = value; }); const body = { text: () => resp.text(), binary: () => resp.buffer(), }; const response = new client.ResponseContext(resp.status, headers, body); return response; }); return resultPromise; } } const configuration = client.createConfiguration({httpApi: new HttpLibraryWithProxy()}); const apiInstance = new v1.DashboardsApi(configuration); apiInstance .listDashboards() .then((data: v1.DashboardSummary) => { console.log( "API called successfully. Returned data: " + JSON.stringify(data) ); }) .catch((error: any) => console.error(error)); ``` -------------------------------- ### Example: Request Cancellation Source: https://github.com/datadog/datadog-api-client-typescript/blob/master/_autodocs/http-transport.md Shows how to cancel an API request using an `AbortController` and `AbortSignal`. The request is aborted after a 5-second delay. ```typescript const controller = new AbortController(); const signal = controller.signal; const configuration = client.createConfiguration({ httpConfig: { signal } }); const apiInstance = new v1.MonitorsApi(configuration); // Start request const promise = apiInstance.listMonitors(); // Cancel after 5 seconds setTimeout(() => controller.abort(), 5000); try { await promise; } catch (error) { if (signal.aborted) { console.log('Request cancelled'); } } ``` -------------------------------- ### Get All Monitors with Details using Pagination Source: https://github.com/datadog/datadog-api-client-typescript/blob/master/_autodocs/examples.md Retrieves all monitors along with their detailed information, including downtimes and assets, by iterating through paginated results. ```typescript async function getAllMonitorsWithDetails() { const monitorsApi = new v1.MonitorsApi(configuration); const monitors = []; for await (const summary of monitorsApi.listMonitorsWithPagination()) { // Get full details for each monitor const full = await monitorsApi.getMonitor({ monitorId: summary.id!, withDowntimes: true, withAssets: true }); monitors.push(full); } return monitors; } ``` -------------------------------- ### Configure Retries with Defaults Source: https://github.com/datadog/datadog-api-client-typescript/blob/master/_autodocs/api-reference/configuration.md Enable automatic retries on 429 and 5xx responses with custom retry settings. This example configures the number of retries and the backoff multiplier. ```typescript const configuration = client.createConfiguration({ enableRetry: true, maxRetries: 5, backoffBase: 2, backoffMultiplier: 1000 // milliseconds }); ``` -------------------------------- ### Basic Usage of Datadog API Client Source: https://github.com/datadog/datadog-api-client-typescript/blob/master/_autodocs/index.md Demonstrates how to create a configuration, instantiate an API client, and make a basic API call to list monitors. Includes error handling for API exceptions. ```typescript import { client, v1 } from '@datadog/datadog-api-client'; // Create configuration (uses DD_API_KEY and DD_APP_KEY env vars) const configuration = client.createConfiguration(); // Create API instance const apiInstance = new v1.MonitorsApi(configuration); // Call an API method try { const monitors = await apiInstance.listMonitors(); console.log('Monitors:', monitors); } catch (error) { if (error instanceof client.ApiException) { console.error(`API Error ${error.code}:`, error.body); } } ``` -------------------------------- ### Hosts API Source: https://github.com/datadog/datadog-api-client-typescript/blob/master/_autodocs/api-reference/v1-overview.md Get host information and tags. This API provides methods to retrieve host totals, list hosts, mute/unmute hosts, get individual host details, and update host tags. ```APIDOC ## HostsApi ### Description Get host information and tags. ### Methods - `getHostTotals` - `listHosts` - `muteHost` - `unmuteHost` - `getHost` - `updateHostTags` ### Key Types - `Host` - `HostTag` ### Example Usage ```typescript const api = new v1.HostsApi(configuration); const hosts = await api.listHosts({ filter: 'env:prod', includeMetadata: true }); ``` ``` -------------------------------- ### Initialize and Use a V1 API Source: https://github.com/datadog/datadog-api-client-typescript/blob/master/_autodocs/api-reference/v1-overview.md Demonstrates the common pattern of initializing a V1 API client and making a request, such as listing monitors. Requires the Datadog API client to be imported and configuration created. ```typescript import { client, v1 } from '@datadog/datadog-api-client'; const configuration = client.createConfiguration(); const api = new v1.MonitorsApi(configuration); const result = await api.listMonitors({ tags: 'env:prod' }); ``` -------------------------------- ### createConfiguration() Source: https://github.com/datadog/datadog-api-client-typescript/blob/master/_autodocs/configuration-auth.md The primary entry point for creating a configured client instance. It accepts an optional `ConfigurationParameters` object to customize the client's behavior, including authentication, server URLs, and retry settings. ```APIDOC ## Function: createConfiguration ### Description Creates a configured Datadog API client instance. Allows customization of authentication, server endpoints, retry behavior, and more. ### Signature ```typescript export function createConfiguration(conf: ConfigurationParameters = {}): Configuration ``` ### Parameters #### ConfigurationParameters Interface ```typescript interface ConfigurationParameters { baseServer?: BaseServerConfiguration; serverIndex?: number; operationServerIndices?: { [name: string]: number }; fetch?: any; httpApi?: HttpLibrary; authMethods?: AuthMethodsConfiguration; httpConfig?: HttpConfiguration; debug?: boolean; zstdCompressorCallback?: ZstdCompressorCallback; maxRetries?: number; backoffBase?: number; backoffMultiplier?: number; enableRetry?: boolean; } ``` ### Defaults - **baseServer:** null - **serverIndex:** 0 - **operationServerIndices:** {} - **httpApi:** IsomorphicFetchHttpLibrary - **authMethods:** Auto-populated from `DD_API_KEY` and `DD_APP_KEY` environment variables - **httpConfig:** {} - **debug:** false - **enableRetry:** false - **maxRetries:** 3 - **backoffBase:** 2 - **backoffMultiplier:** 2 ### Example: Explicit Authentication ```typescript import { client } from '@datadog/datadog-api-client'; const configuration = client.createConfiguration({ authMethods: { apiKeyAuth: 'sk_test_abc123', appKeyAuth: 'app_key_xyz789' } }); ``` ### Example: Enable Retries ```typescript const configuration = client.createConfiguration({ enableRetry: true, maxRetries: 5, backoffBase: 2, backoffMultiplier: 2 }); ``` ### Example: Disable Compression ```typescript const configuration = client.createConfiguration({ httpConfig: { compress: false } }); ``` ``` -------------------------------- ### Response Processing Example Source: https://github.com/datadog/datadog-api-client-typescript/blob/master/_autodocs/http-transport.md Deserializes the ResponseContext, parsing the body based on its content type. ```typescript const contentType = ObjectSerializer.normalizeMediaType( responseContext.headers["content-type"] ); const body = ObjectSerializer.deserialize( ObjectSerializer.parse(await responseContext.body.text(), contentType), "Monitor" ) as Monitor; ``` -------------------------------- ### Datadog API Client Authentication with Environment Variables Source: https://github.com/datadog/datadog-api-client-typescript/blob/master/_autodocs/index.md Sets up authentication for the Datadog API client using environment variables for API key, application key, and optionally the Datadog site. ```bash export DD_API_KEY=your_api_key export DD_APP_KEY=your_app_key export DD_SITE=datadoghq.com # Optional: default endpoint ``` -------------------------------- ### createConfiguration Factory Function Source: https://github.com/datadog/datadog-api-client-typescript/blob/master/_autodocs/api-reference/configuration.md The recommended way to create a Configuration instance. It automatically loads credentials from environment variables and initializes default values. ```APIDOC ## createConfiguration Factory Function ### Description This factory function creates a `Configuration` instance, automatically loading credentials from environment variables (`DD_API_KEY`, `DD_APP_KEY`, `DD_SITE`) and setting up default values for all options. ### Signature ```typescript export function createConfiguration(conf?: ConfigurationParameters): Configuration ``` ### Parameters #### ConfigurationParameters - **baseServer** (BaseServerConfiguration) - Optional - Override server URL entirely. - **serverIndex** (number) - Optional - Index into predefined servers list (default: 0). - **operationServerIndices** ({ [name: string]: number }) - Optional - Per-operation server selection. - **fetch** (any) - Optional - Custom fetch implementation. - **httpApi** (HttpLibrary) - Optional - Custom HTTP transport (default: IsomorphicFetchHttpLibrary). - **authMethods** (AuthMethodsConfiguration) - Optional - Authentication setup (default: Auto from env vars). - **httpConfig** (HttpConfiguration) - Optional - HTTP options (compression, signals) (default: {}). - **debug** (boolean) - Optional - Enable request/response logging (default: false). - **zstdCompressorCallback** (ZstdCompressorCallback) - Optional - Custom Zstd compression. - **maxRetries** (number) - Optional - Max automatic retry attempts (default: 3). - **backoffBase** (number) - Optional - Exponential backoff base (min 2) (default: 2). - **backoffMultiplier** (number) - Optional - Backoff multiplier per retry (default: 2). - **enableRetry** (boolean) - Optional - Enable automatic retries on 429/5xx (default: false). ### Example: Default Configuration ```typescript import { client } from '@datadog/datadog-api-client'; // Uses environment variables: DD_API_KEY, DD_APP_KEY, DD_SITE const configuration = client.createConfiguration(); ``` ### Example: Explicit Parameters ```typescript const configuration = client.createConfiguration({ authMethods: { apiKeyAuth: 'my_api_key', appKeyAuth: 'my_app_key' }, httpConfig: { compress: true }, debug: true, enableRetry: true, maxRetries: 5 }); ``` ``` -------------------------------- ### Get Dashboard Source: https://github.com/datadog/datadog-api-client-typescript/blob/master/_autodocs/api-reference/v1-overview.md Use the DashboardsApi to retrieve a specific dashboard by its ID. Ensure the `v1` module is imported. ```typescript import { v1 } from '@datadog/datadog-api-client'; const api = new v1.DashboardsApi(configuration); const dashboard = await api.getDashboard({ dashboardId: 'abc-123' }); ``` -------------------------------- ### Create API Instance Source: https://github.com/datadog/datadog-api-client-typescript/blob/master/_autodocs/README.md Instantiates a service-specific API class, such as MonitorsApi, using a provided Configuration instance. This prepares the client for making API calls. ```typescript const api = new v1.MonitorsApi(configuration); ``` -------------------------------- ### Create Default Configuration Source: https://github.com/datadog/datadog-api-client-typescript/blob/master/_autodocs/api-reference/configuration.md Creates a Configuration instance using default settings. It automatically loads API keys, app keys, and site from environment variables. ```typescript import { client } from '@datadog/datadog-api-client'; // Uses environment variables: DD_API_KEY, DD_APP_KEY, DD_SITE const configuration = client.createConfiguration(); ``` -------------------------------- ### Logs Indexes API Source: https://github.com/datadog/datadog-api-client-typescript/blob/master/_autodocs/api-reference/v1-overview.md Manage log indexes. This API provides methods to get, list, and update log indexes. ```APIDOC ## LogsIndexesApi ### Description Manage log indexes. ### Methods - `getLogIndex` - `getLogIndexOrder` - `listLogIndexes` - `updateLogIndex` - `updateLogIndexOrder` ### Key Types - `LogIndex` ``` -------------------------------- ### List Hosts with Filters Source: https://github.com/datadog/datadog-api-client-typescript/blob/master/_autodocs/api-reference/v1-overview.md Initialize the Hosts API client and list hosts, applying a filter for production environment and including metadata. ```typescript const api = new v1.HostsApi(configuration); const hosts = await api.listHosts({ filter: 'env:prod', includeMetadata: true }); ``` -------------------------------- ### Get Server for Operation Source: https://github.com/datadog/datadog-api-client-typescript/blob/master/_autodocs/http-transport.md Retrieve the appropriate server configuration for a specific API operation. This is used to create a request context for routing. ```typescript const server = configuration.getServer("v1.MonitorsApi.listMonitors"); const requestContext = server.makeRequestContext( "/api/v1/monitor", HttpMethod.GET ); ``` -------------------------------- ### Initialize Client with Environment Variables Source: https://github.com/datadog/datadog-api-client-typescript/blob/master/_autodocs/examples.md Initializes the Datadog API client using DD_API_KEY and DD_APP_KEY environment variables. This is the recommended approach for most applications. ```typescript import { client, v1 } from '@datadog/datadog-api-client'; // Uses DD_API_KEY and DD_APP_KEY environment variables const configuration = client.createConfiguration(); const monitorsApi = new v1.MonitorsApi(configuration); ``` -------------------------------- ### Get Datadog IP Ranges Source: https://github.com/datadog/datadog-api-client-typescript/blob/master/_autodocs/api-reference/v1-overview.md Retrieve Datadog IP ranges using the IPRangesApi. Ensure the API client is initialized with the correct configuration. ```typescript const api = new v1.IPRangesApi(configuration); const ranges = await api.getIPRanges(); ``` -------------------------------- ### Project File Organization Source: https://github.com/datadog/datadog-api-client-typescript/blob/master/_autodocs/README.md Illustrates the directory structure of the Datadog API Client TypeScript project. ```bash output/ ├── README.md # This file ├── index.md # Main overview ├── configuration-auth.md # Setup and authentication ├── http-transport.md # HTTP layer details ├── errors.md # Error handling ├── types.md # Data types ├── examples.md # Usage examples └── api-reference/ ├── configuration.md # Configuration class ├── authentication-api.md # Auth API reference ├── monitors-api.md # Monitors API reference └── v1-overview.md # All V1 APIs overview ``` -------------------------------- ### Import and Use Common Client Types Source: https://github.com/datadog/datadog-api-client-typescript/blob/master/_autodocs/types.md Demonstrates importing and using common types from the root '@datadog/datadog-api-client' namespace, such as 'Configuration' and 'ApiException'. It includes creating a configuration object. ```typescript import { client } from '@datadog/datadog-api-client'; // Configuration types const config: client.Configuration = client.createConfiguration(); const exception: client.ApiException = ...; ``` -------------------------------- ### List Logs with Query Source: https://github.com/datadog/datadog-api-client-typescript/blob/master/_autodocs/api-reference/v1-overview.md Initialize the Logs API client and list logs based on a specific query. ```typescript const api = new v1.LogsApi(configuration); const logs = await api.listLogs({ body: { query: 'service:my_service status:error' } }); ``` -------------------------------- ### Get Specific Monitor Source: https://github.com/datadog/datadog-api-client-typescript/blob/master/_autodocs/examples.md Retrieves detailed information about a specific monitor by its ID. Includes options to fetch associated downtime and asset information. ```typescript const monitor = await monitorsApi.getMonitor({ monitorId: 123, groupStates: 'alert', withDowntimes: true, withAssets: true }); console.log('Name:', monitor.name); console.log('Type:', monitor.type); console.log('Query:', monitor.query); console.log('State:', monitor.overallState); ``` -------------------------------- ### Use V1 and V2 APIs Together Source: https://github.com/datadog/datadog-api-client-typescript/blob/master/_autodocs/api-reference/v1-overview.md Demonstrates how to import and instantiate clients for both v1 and v2 of the Datadog API within the same application. This allows leveraging features from both versions concurrently. ```typescript import { v1, v2 } from '@datadog/datadog-api-client'; const v1Monitors = new v1.MonitorsApi(configuration); const v2Incidents = new v2.IncidentsApi(configuration); ``` -------------------------------- ### SecurityAuthentication Interface Source: https://github.com/datadog/datadog-api-client-typescript/blob/master/_autodocs/types.md Defines the interface for authentication scheme implementations. It includes methods to get the authentication scheme name and apply it to a request context. ```typescript export interface SecurityAuthentication { getName(): string; applySecurityAuthentication(context: RequestContext): void; } ``` -------------------------------- ### Handling API Errors by HTTP Status Code Source: https://github.com/datadog/datadog-api-client-typescript/blob/master/_autodocs/errors.md Provides a detailed example of handling different API errors based on their HTTP status codes. ```APIDOC ### HTTP Status Code Handling ```typescript try { await monitorsApi.getMonitor({ monitorId: 123 }); } catch (error) { if (error instanceof client.ApiException) { switch (error.code) { case 200: case 201: case 204: // Success (should not throw) break; case 400: // Bad request - malformed parameters console.error('Invalid parameters:', error.body); break; case 401: // Unauthorized - missing credentials console.error('Authentication required'); break; case 403: // Forbidden - insufficient permissions or invalid API key console.error('Access denied. Check API key and permissions.'); break; case 404: // Not found - resource doesn't exist console.error('Resource not found'); break; case 409: // Conflict - state mismatch (e.g., monitor already exists) console.error('Conflict:', error.body); break; case 429: // Rate limited - too many requests console.error('Rate limited. Retry after a delay.'); break; case 500: case 502: case 503: case 504: // Server error console.error('Server error. Retry later.'); break; default: console.error(`Unexpected error ${error.code}:`, error.body); } } } ``` ``` -------------------------------- ### Create Configuration with Explicit Parameters Source: https://github.com/datadog/datadog-api-client-typescript/blob/master/_autodocs/api-reference/configuration.md Creates a Configuration instance by explicitly providing various parameters. This allows for fine-grained control over authentication, HTTP options, debugging, and retries. ```typescript const configuration = client.createConfiguration({ authMethods: { apiKeyAuth: 'my_api_key', appKeyAuth: 'my_app_key' }, httpConfig: { compress: true }, debug: true, enableRetry: true, maxRetries: 5 }); ``` -------------------------------- ### Configuration Class Methods Source: https://github.com/datadog/datadog-api-client-typescript/blob/master/_autodocs/configuration-auth.md Methods available on the `Configuration` object, instantiated by `createConfiguration()`, for managing server settings and retrieving server configurations. ```APIDOC ## Class: Configuration ### Method: setServerVariables() Sets server URL template variables for the current configuration. #### Signature ```typescript setServerVariables(serverVariables: { [key: string]: string }): void ``` #### Parameters - **serverVariables** (object) - Object with site, subdomain, or name keys depending on server configuration. #### Example ```typescript const configuration = client.createConfiguration(); configuration.setServerVariables({ site: 'datadoghq.eu' }); ``` ### Method: getServer() Gets the server configuration for a specific endpoint. #### Signature ```typescript getServer(endpoint: string): BaseServerConfiguration ``` #### Parameters - **endpoint** (string) - Operation name (e.g., 'v1.MonitorsApi.getMonitor'). #### Returns - **BaseServerConfiguration** - Server configuration with URL template applied. ``` -------------------------------- ### Create and Validate a Monitor Source: https://github.com/datadog/datadog-api-client-typescript/blob/master/_autodocs/api-reference/monitors-api.md First, validate a monitor configuration using `validateMonitor`. If valid, proceed to create the monitor using `createMonitor`. ```typescript const monitorConfig: v1.Monitor = { type: v1.MonitorType.METRIC_ALERT, query: 'avg:metric{*}', name: 'My Monitor' }; // Validate first await monitorsApi.validateMonitor({ body: monitorConfig }); // Then create const created = await monitorsApi.createMonitor({ body: monitorConfig }); ``` -------------------------------- ### Server Configuration - Supported Sites Source: https://github.com/datadog/datadog-api-client-typescript/blob/master/_autodocs/configuration-auth.md Lists the supported Datadog sites/regions. ```APIDOC ### Supported Sites ``` datadoghq.com (US) us3.datadoghq.com (US3) us5.datadoghq.com (US5) ap1.datadoghq.com (AP1) ap2.datadoghq.com (AP2) datadoghq.eu (EU) ddog-gov.com (US Gov) us2.ddog-gov.com (US Gov 2) ``` ``` -------------------------------- ### Logs Pipelines API Source: https://github.com/datadog/datadog-api-client-typescript/blob/master/_autodocs/api-reference/v1-overview.md Manage log processing pipelines. This API allows for creating, deleting, getting, listing, and updating log processing pipelines. ```APIDOC ## LogsPipelinesApi ### Description Manage log processing pipelines. ### Methods - `getLogsPipeline` - `getLogsPipelineOrder` - `listLogsPipelines` - `createLogsPipeline` - `deleteLogsPipeline` - `updateLogsPipeline` - `updateLogsPipelineOrder` ### Key Types - `LogsPipeline` - `LogsProcessor` ``` -------------------------------- ### Create Downtime Source: https://github.com/datadog/datadog-api-client-typescript/blob/master/_autodocs/api-reference/v1-overview.md Use the DowntimesApi to create a new downtime, specifying the monitor ID, start, and end times. Ensure the `v1` module is imported. ```typescript import { v1 } from '@datadog/datadog-api-client'; const api = new v1.DowntimesApi(configuration); const downtime = await api.createDowntime({ body: { monitorId: 123, start: Math.floor(Date.now() / 1000), end: Math.floor(Date.now() / 1000) + 3600 } }); ``` -------------------------------- ### List Tags Source: https://github.com/datadog/datadog-api-client-typescript/blob/master/_autodocs/api-reference/v1-overview.md Initialize the Tags API client and list all available tags. ```typescript const api = new v1.TagsApi(configuration); const tags = await api.listTags(); ``` -------------------------------- ### Environment Variables Source: https://github.com/datadog/datadog-api-client-typescript/blob/master/_autodocs/configuration-auth.md Lists environment variables used for configuration. ```APIDOC ## Environment Variables The client reads these environment variables during `createConfiguration()`: | Variable | Purpose | Example | |----------|---------|---------| | `DD_API_KEY` | Datadog API key | `sk_live_abc123...` | | `DD_APP_KEY` | Datadog application key | `app_abc123...` | | `DD_SITE` | Datadog site/region | `datadoghq.eu` | **Note:** Explicitly provided `authMethods` in ConfigurationParameters take precedence over environment variables. ``` -------------------------------- ### Get a Specific Monitor Source: https://github.com/datadog/datadog-api-client-typescript/blob/master/_autodocs/api-reference/monitors-api.md Retrieve detailed information for a single monitor using its ID. Supports filtering by group states and including associated downtimes or assets. ```typescript const monitor = await monitorsApi.getMonitor({ monitorId: 123, groupStates: 'alert,ok', withDowntimes: true, withAssets: true }); console.log('Monitor:', monitor.name); console.log('Type:', monitor.type); console.log('Query:', monitor.query); console.log('Created:', monitor.created); ``` -------------------------------- ### Get Server Configuration for an Endpoint Source: https://github.com/datadog/datadog-api-client-typescript/blob/master/_autodocs/api-reference/configuration.md Retrieve the server configuration for a specific API endpoint. The API request factory uses this internally to construct the correct request context. ```typescript // In MonitorsApiRequestFactory.listMonitors() const server = configuration.getServer("v1.MonitorsApi.listMonitors"); const requestContext = server.makeRequestContext("/api/v1/monitor", HttpMethod.GET); ``` -------------------------------- ### Handle Rate Limiting Error (429) Source: https://github.com/datadog/datadog-api-client-typescript/blob/master/_autodocs/errors.md Implement a strategy to handle API rate limiting errors (HTTP 429). This example shows waiting for a specified duration before retrying the request. ```typescript const sleep = (ms: number) => new Promise(r => setTimeout(r, ms)); try { await monitorsApi.listMonitors(); } catch (error) { if (error instanceof client.ApiException && error.code === 429) { console.error('Rate limited. Waiting before retry...'); await sleep(60000); // Wait 60 seconds await monitorsApi.listMonitors(); // Retry } } ``` -------------------------------- ### Handling API Errors by HTTP Status Code Source: https://github.com/datadog/datadog-api-client-typescript/blob/master/_autodocs/errors.md Provides a detailed example of handling API errors by inspecting the HTTP status code within an ApiException. This allows for specific recovery logic based on the error type. ```typescript try { await monitorsApi.getMonitor({ monitorId: 123 }); } catch (error) { if (error instanceof client.ApiException) { switch (error.code) { case 200: case 201: case 204: // Success (should not throw) break; case 400: // Bad request - malformed parameters console.error('Invalid parameters:', error.body); break; case 401: // Unauthorized - missing credentials console.error('Authentication required'); break; case 403: // Forbidden - insufficient permissions or invalid API key console.error('Access denied. Check API key and permissions.'); break; case 404: // Not found - resource doesn't exist console.error('Resource not found'); break; case 409: // Conflict - state mismatch (e.g., monitor already exists) console.error('Conflict:', error.body); break; case 429: // Rate limited - too many requests console.error('Rate limited. Retry after a delay.'); break; case 500: case 502: case 503: case 504: // Server error console.error('Server error. Retry later.'); break; default: console.error(`Unexpected error ${error.code}:`, error.body); } } } ``` -------------------------------- ### Server Selection Strategy Source: https://github.com/datadog/datadog-api-client-typescript/blob/master/_autodocs/api-reference/configuration.md Understand and configure how the API client selects server endpoints, including global defaults, per-operation overrides, and custom server variables. ```APIDOC ## Server Selection Strategy The client selects servers in the following order: 1. **`baseServer`**: If explicitly set, it overrides all other configurations. 2. **`operationServerIndices`**: If an index is specified for a particular endpoint, it takes precedence over the default server index. 3. **`serverIndex`**: The default server index (usually 0) is used if no other overrides are applied. ### `servers` Property An array containing all available server configurations. ```typescript servers: BaseServerConfiguration[] ``` ### `operationServers` Property A dictionary to specify per-operation server overrides. ```typescript operationServers: { [endpoint: string]: BaseServerConfiguration[] } ``` ### `setServerVariables()` Method Set URL template variables for the current server selection. This allows customization of server URLs based on parameters like region or subdomain. ```typescript public setServerVariables(serverVariables: { [key: string]: string }): void ``` **Parameters:** | Parameter | Type | Description | |-----------|------|-------------| | serverVariables | { [key: string]: string } | Variables to substitute in server URL template | **Available Variables (depends on server):** - `site`: Datadog region/site (e.g., `datadoghq.com`, `datadoghq.eu`). - `subdomain`: Custom subdomain (default: `api`). - `name`: Full hostname (alternative to `subdomain`/`site`). - `protocol`: Protocol (`http` or `https`). **Example: Switch to EU** ```typescript const configuration = client.createConfiguration(); configuration.setServerVariables({ site: 'datadoghq.eu' }); ``` **Example: Custom Subdomain** ```typescript configuration.setServerVariables({ subdomain: 'custom', site: 'datadoghq.com' }); // Results in: https://custom.datadoghq.com ``` ### `getServer()` Method Retrieves the server configuration for a specific operation, with URL variables applied. ```typescript public getServer(endpoint: string): BaseServerConfiguration ``` **Parameters:** | Parameter | Type | Description | |-----------|------|-------------| | endpoint | string | Operation name (e.g., `'v1.MonitorsApi.listMonitors'`) | **Returns:** `BaseServerConfiguration` for that endpoint, with URL variables applied. **Usage (internal):** The API request factory uses this internally. ```typescript // In MonitorsApiRequestFactory.listMonitors() const server = configuration.getServer("v1.MonitorsApi.listMonitors"); const requestContext = server.makeRequestContext("/api/v1/monitor", HttpMethod.GET); ``` ### Supported Servers **Server 0 (Default):** ``` https://{subdomain}.{site} Variables: { subdomain: "api", site: "datadoghq.com" } Result: https://api.datadoghq.com ``` **Server 1:** ``` {protocol}://{name} Variables: { protocol: "https", name: "api.datadoghq.com" } Result: https://api.datadoghq.com ``` **Server 2:** ``` https://{subdomain}.{site} Variables: { subdomain: "api", site: "datadoghq.com" } Result: https://api.datadoghq.com (same as Server 0) ``` ``` -------------------------------- ### List Service Level Objectives (SLOs) Source: https://github.com/datadog/datadog-api-client-typescript/blob/master/_autodocs/api-reference/v1-overview.md Initialize the Service Level Objectives API client and list all configured SLOs. ```typescript const api = new v1.ServiceLevelObjectivesApi(configuration); const slos = await api.listSLOs(); ``` -------------------------------- ### List Users Source: https://github.com/datadog/datadog-api-client-typescript/blob/master/_autodocs/api-reference/v1-overview.md Initialize the Users API client and list all users in the organization. ```typescript const api = new v1.UsersApi(configuration); const users = await api.listUsers(); ``` -------------------------------- ### Create Configuration with Custom HTTP Library Source: https://github.com/datadog/datadog-api-client-typescript/blob/master/_autodocs/api-reference/configuration.md Implement a custom HTTP library by extending the HttpLibrary interface. This allows for custom request handling and response processing. ```typescript import { client } from '@datadog/datadog-api-client'; class CustomHttpLibrary implements client.HttpLibrary { async send(requestContext: client.RequestContext): Promise { // Custom implementation const response = await myHttpClient.request({ url: requestContext.getUrl(), method: requestContext.getHttpMethod(), headers: requestContext.getHeaders(), body: requestContext.getBody() }); return new client.ResponseContext( response.status, response.headers, response.body ); } } const configuration = client.createConfiguration({ httpApi: new CustomHttpLibrary() }); ``` -------------------------------- ### RequestContext setHttpConfig() Method Source: https://github.com/datadog/datadog-api-client-typescript/blob/master/_autodocs/http-transport.md Sets HTTP configuration options, such as enabling compression or providing an AbortSignal for cancellation. ```typescript public setHttpConfig(httpConfig: HttpConfiguration): void ``` -------------------------------- ### Create Configuration Source: https://github.com/datadog/datadog-api-client-typescript/blob/master/_autodocs/README.md Factory method to create a Configuration instance for the Datadog API client. Manages client settings like authentication, server selection, and HTTP transport. ```typescript const configuration = client.createConfiguration(); ``` -------------------------------- ### BaseServerConfiguration Class Source: https://github.com/datadog/datadog-api-client-typescript/blob/master/_autodocs/types.md Configuration class for server URL templates, allowing dynamic variable setting and request context creation. ```typescript export class BaseServerConfiguration { public constructor( url: string, variableConfiguration: { [key: string]: string } ) public setVariables( variableConfiguration: { [key: string]: string } ): void public getConfiguration(): { [key: string]: string } public clone(): BaseServerConfiguration public makeRequestContext( endpoint: string, httpMethod: HttpMethod ): RequestContext } ``` -------------------------------- ### Create a New Monitor Source: https://github.com/datadog/datadog-api-client-typescript/blob/master/_autodocs/api-reference/monitors-api.md Create a new Datadog monitor by providing a detailed monitor configuration object. The response includes the ID of the newly created monitor. ```typescript const monitor: v1.Monitor = { type: v1.MonitorType.METRIC_ALERT, query: 'avg:system.cpu{*} by {host}', name: 'CPU Alert', message: 'Alert when CPU is high {{#is_alert}}@pagerduty{{/is_alert}}', tags: ['env:prod', 'team:backend'], priority: 2, options: { thresholds: { critical: 0.9 }, notificationPresets: v1.NotificationPresetType.SHOW_ALL, includeMetadata: true } }; const created = await monitorsApi.createMonitor({ body: monitor }); console.log('Created monitor ID:', created.id); ``` -------------------------------- ### Enable GZIP Compression Source: https://github.com/datadog/datadog-api-client-typescript/blob/master/_autodocs/http-transport.md Enable GZIP compression for requests to reduce bandwidth. This is the default setting. ```typescript const configuration = client.createConfiguration({ httpConfig: { compress: true } // Default }); ``` -------------------------------- ### Server Configuration - Available Servers Source: https://github.com/datadog/datadog-api-client-typescript/blob/master/_autodocs/configuration-auth.md Details the predefined servers available for endpoint selection. ```APIDOC ## Server Configuration ### Available Servers The client has three predefined servers for flexibility in endpoint selection: **Server 1 (Recommended):** ``` https://{subdomain}.{site} Default: https://api.datadoghq.com ``` **Server 2:** ``` {protocol}://{name} Default: https://api.datadoghq.com ``` **Server 3:** ``` https://{subdomain}.{site} Default: https://api.datadoghq.com ``` ``` -------------------------------- ### listMonitorsWithPagination() Source: https://github.com/datadog/datadog-api-client-typescript/blob/master/_autodocs/api-reference/monitors-api.md A paginated version of `listMonitors()` that allows for iterating through monitors one at a time using an async generator. ```APIDOC ## GET /api/v1/monitor (Paginated) ### Description Paginated version of `listMonitors()` that yields monitors one at a time. ### Method GET ### Endpoint /api/v1/monitor ### Parameters #### Query Parameters - **groupStates** (string) - Optional - Comma-separated group state values to filter. - **name** (string) - Optional - Filter monitors by name. - **tags** (string) - Optional - Filter by organization tags. - **monitorTags** (string) - Optional - Filter by monitor tags. - **withDowntimes** (boolean) - Optional - Include matching downtimes. - **idOffset** (number) - Optional - Monitor ID offset for pagination. - **page** (number) - Optional - Page number for pagination. - **pageSize** (number) - Optional - Number of monitors per page (max 100). ### Request Example ```typescript for await (const monitor of monitorsApi.listMonitorsWithPagination({ tags: 'env:prod' })) { console.log(monitor.name, monitor.id); } ``` ### Response #### Success Response (200) - **id** (number) - The ID of the monitor. - **name** (string) - The name of the monitor. - **type** (string) - The type of the monitor. #### Response Example ```json { "id": 123, "name": "My Monitor", "type": "metric alert" } ``` ``` -------------------------------- ### List Synthetics Tests Source: https://github.com/datadog/datadog-api-client-typescript/blob/master/_autodocs/api-reference/v1-overview.md Initialize the Synthetics API client and list all available synthetic tests. ```typescript const api = new v1.SyntheticsApi(configuration); const tests = await api.listSyntheticsTests(); ``` -------------------------------- ### Create and Manage Datadog Monitors Source: https://github.com/datadog/datadog-api-client-typescript/blob/master/_autodocs/examples.md Demonstrates how to create, list, disable, and delete monitors using the Datadog API client. This class encapsulates monitor management operations. ```typescript class DatadogMonitorManager { private monitorsApi: v1.MonitorsApi; constructor(configuration: client.Configuration) { this.monitorsApi = new v1.MonitorsApi(configuration); } async createAlertMonitor( name: string, query: string, threshold: number, tags: string[] ): Promise { const monitor: v1.Monitor = { name, type: v1.MonitorType.METRIC_ALERT, query, tags, options: { thresholds: { critical: threshold }, notificationPresets: v1.NotificationPresetType.SHOW_ALL } }; return this.monitorsApi.createMonitor({ body: monitor }); } async listProductionMonitors(): Promise { const monitors = await this.monitorsApi.listMonitors({ tags: 'env:prod' }); return monitors; } async disableMonitor(id: number): Promise { const current = await this.monitorsApi.getMonitor({ monitorId: id }); // Implementation depends on monitor type } async deleteMonitor(id: number): Promise { const canDelete = await this.monitorsApi.checkCanDeleteMonitor({ monitorIds: [id] }); if (!canDelete.ok) { throw new Error(`Cannot delete monitor: ${canDelete.errors}`); } await this.monitorsApi.deleteMonitor({ monitorId: id }); } } // Usage const manager = new DatadogMonitorManager(configuration); const monitor = await manager.createAlertMonitor( 'My Alert', 'avg:metric{*}', 100, ['env:prod'] ); ``` -------------------------------- ### Initialize Client with Explicit Credentials Source: https://github.com/datadog/datadog-api-client-typescript/blob/master/_autodocs/examples.md Initializes the Datadog API client by explicitly providing API and application keys. Ensure these keys are kept secure. ```typescript const configuration = client.createConfiguration({ authMethods: { apiKeyAuth: 'sk_live_your_api_key_here', appKeyAuth: 'your_app_key_here' } }); ``` -------------------------------- ### Usage Pattern: Validation with Custom Configuration Source: https://github.com/datadog/datadog-api-client-typescript/blob/master/_autodocs/api-reference/authentication-api.md Illustrates how to override default configuration with a custom configuration, including a different API key, for a specific validation call. ```typescript const customConfig = client.createConfiguration({ authMethods: { apiKeyAuth: 'custom_key_for_this_call' } }); const authApi = new v1.AuthenticationApi(defaultConfig); // Override with custom config for this call await authApi.validate(customConfig); ``` -------------------------------- ### List Azure Integrations Source: https://github.com/datadog/datadog-api-client-typescript/blob/master/_autodocs/api-reference/v1-overview.md Use the AzureIntegrationApi to list configured Azure integrations. Ensure the `v1` module is imported. ```typescript import { v1 } from '@datadog/datadog-api-client'; const api = new v1.AzureIntegrationApi(configuration); const integrations = await api.listAzureIntegration(); ```