Note
The next major version iteration of @datadog/datadog-api-client, v2, is now in Preview.
The v2 splits the monolithic client into new logically grouped api package structure.
See MIGRATION.md and the v2 branch branch for more details.
This repository contains a Node.js API client for the Datadog API.
The package is under @datadog/datadog-api-client and can be installed through NPM or Yarn:
# NPM
npm install @datadog/datadog-api-client
# Yarn
yarn add @datadog/datadog-api-clientHere's an example getting a monitor:
import{client,v1}from'@datadog/datadog-api-client';constconfiguration=client.createConfiguration();constapiInstance=newv1.MonitorsApi(configuration);letparams:v1.MonitorsApiGetMonitorRequest={// number | The ID of the monitormonitorId: 1,};apiInstance.getMonitor(params).then((data: v1.Monitor)=>{console.log('API called successfully. Returned data: '+data);}).catch((error:any)=>console.error(error));By default the library will use the DD_API_KEY and DD_APP_KEY environment variables to authenticate against the Datadog API.
To provide your own set of credentials, you need to set the appropriate keys on the configuration:
import{client}from'@datadog/datadog-api-client';constconfigurationOpts={authMethods: {apiKeyAuth: "<API KEY>",appKeyAuth: "<APPLICATION KEY>"},};constconfiguration=client.createConfiguration(configurationOpts);This client includes access to Datadog API endpoints while they are in an unstable state and may undergo breaking changes. An extra configuration step is required to enable these endpoints:
configuration.unstableOperations["<version>.<operationName>"]=truewhere <operationName> is the name of the method used to interact with that endpoint. For example: listLogIndexes, or getLogsIndex.
When talking to a different server, like the eu instance, change the server variables:
import{client}from'@datadog/datadog-api-client';constconfiguration=client.createConfiguration();configuration.setServerVariables({site: "datadoghq.eu"});If you want to disable GZIP compressed responses, set the compress flag
on your configuration options:
import{client}from'@datadog/datadog-api-client';constconfigurationOpts={httpConfig: {compress: false},};constconfiguration=client.createConfiguration(configurationOpts);If you want to enable requests logging, set the debug flag on your configuration object:
import{client}from'@datadog/datadog-api-client';constconfigurationOpts={debug: true};constconfiguration=client.createConfiguration(configurationOpts);To enable the client to retry when rate limited (status 429) or status 500 and above:
import{client}from'@datadog/datadog-api-client';constconfigurationOpts={enableRetry: true};constconfiguration=client.createConfiguration(configurationOpts);The interval between 2 retry attempts will be the value of the x-ratelimit-reset response header when available. If not, it will be :
(backoffMultiplier**current_retry_count)*backoffBaseThe maximum number of retry attempts is 3 by default and can be modified with
maxRetriesTo add timeout or other mechanism to cancel requests, you need an abort controller, for example the one implemented by abort-controller. You can then pass the `signal method to the HTTP configuration options:
import{client,v1}from'@datadog/datadog-api-client';importAbortControllerfrom'abort-controller';constcontroller=newAbortController();consttimeout=setTimeout(()=>{controller.abort();},1000,);constconfigurationOpts={httpConfig: {signal: controller.signal},};constconfiguration=client.createConfiguration(configurationOpts);constapiInstance=newv1.MonitorsApi(configuration);apiInstance.listMonitors().then((data: v1.Monitor[])=>{console.log('API called successfully. Returned data: '+data);}).catch((error:any)=>console.error(error)).finally(()=>clearTimeout(timeout));Several listing operations have a pagination method to help consume all the items available. For example, to retrieve all your incidents:
import{client,v2}from"@datadog/datadog-api-client";asyncfunctionmain(){constconfiguration=client.createConfiguration();configuration.unstableOperations["v2.listIncidents"]=true;constapiInstance=newv2.IncidentsApi(configuration);forawait(constincidentofapiInstance.listIncidentsWithPagination()){console.log("Got incident "+incident.id);}}main();Zstd compression support requires users to supply their own zstd compressor callback function.
The callback should accept string arg and return compressed Buffer data.
Callback signature (body: string) => Buffer.
For example, using zstd.ts package:
import{compressSync}from'zstd.ts'import{client,v2}from"@datadog/datadog-api-client";asyncfunctionmain(){constconfigurationOpts={zstdCompressorCallback: (body: string)=>compressSync({input: Buffer.from(body,"utf8")})}constconfiguration=client.createConfiguration(configurationOpts);constapiInstance=newv2.MetricsApi(configuration);constparams: v2.MetricsApiSubmitMetricsRequest={body: {series: [{metric: "system.load.1",type: 0,points: [{timestamp: Math.round(newDate().getTime()/1000),value: 0.7,},],},],},contentEncoding: "zstd1",};apiInstance.submitMetrics(params).then((data: v2.IntakePayloadAccepted)=>{console.log("API called successfully. Returned data: "+JSON.stringify(data));}).catch((error: any)=>console.error(error));}main();You can provide custom HttpLibrary implementation with proxy support to configuration object. See example below:
importpakofrom"pako";importbufferFromfrom"buffer-from";importfetchfrom"node-fetch";import{HttpsProxyAgent}from"https-proxy-agent";import{v1,client}from"@datadog/datadog-api-client";constproxyAgent=newHttpsProxyAgent('http://127.0.0.11:3128');classHttpLibraryWithProxyimplementsclient.HttpLibrary{publicdebug=false;publicsend(request: client.RequestContext): Promise<client.ResponseContext>{constmethod=request.getHttpMethod().toString();letbody=request.getBody();letcompress=request.getHttpConfig().compress;if(compress===undefined){compress=true;}constheaders=request.getHeaders();if(typeofbody==="string"){if(headers["Content-Encoding"]==="gzip"){body=bufferFrom(pako.gzip(body).buffer);}elseif(headers["Content-Encoding"]==="deflate"){body=bufferFrom(pako.deflate(body).buffer);}}constresultPromise=fetch(request.getUrl(),{method: method,body: bodyasany,headers: headers,signal: request.getHttpConfig().signal,compress: compress,agent: proxyAgent,}).then((resp: any)=>{constheaders: {[name: string]: string}={};resp.headers.forEach((value: string,name: string)=>{headers[name]=value;});constbody={text: ()=>resp.text(),binary: ()=>resp.buffer(),};constresponse=newclient.ResponseContext(resp.status,headers,body);returnresponse;});returnresultPromise;}}constconfiguration=client.createConfiguration({httpApi: newHttpLibraryWithProxy()});constapiInstance=newv1.DashboardsApi(configuration);apiInstance.listDashboards().then((data: v1.DashboardSummary)=>{console.log("API called successfully. Returned data: "+JSON.stringify(data));}).catch((error: any)=>console.error(error));Documentation for API endpoints can be found in GitHub pages.
As most of the code in this repository is generated, we will only accept PRs for files that are not modified by our code-generation machinery (changes to the generated files would get overwritten). We happily accept contributions to files that are not autogenerated, such as tests and development tooling.