Datadog API Client Libraries Now Available for Java and Go | Datadog

Datadog API client libraries now available for Java and Go

Author Jordan Obey

Published: 7月 20, 2020

Client libraries are collections of code that make it easier for developers to write flexible and efficient applications that interface with APIs. Datadog provides client libraries so you can programmatically interact with our API to customize dashboards, search metrics, create alerts, and perform other tasks. We’re pleased to announce that we’ve developed and open-sourced two new client libraries for Java and Go in addition to our existing Ruby and Python libraries.

Now, development teams who work closely with either Java or Go can build applications that programmatically execute Datadog-specific tasks, including building dashboards, retrieving metric data, and managing your account. These libraries were generated with the OpenAPI Generator and adhere to the OpenAPI Specification (formerly known as the Swagger Specification), which means developers can easily contribute to them.

In this post we’ll show you how to import our Java and Go client libraries into your application code. Then, we’ll look at a few usage examples, including how to get and update dashboards, list metrics, and retrieve logs. Please note that while the code samples included in this post are written in Go, the same functionality is available in Java. You can use our API reference documentation for more guidance on using any of these libraries.

Getting started with the Java and Go client libraries

Once you’ve installed the Datadog Agent in your environment, client libraries can be used to send and view data through the Datadog API. To use the Go client library in your application, you’ll simply need to import it with the following:

import "github.com/DataDog/datadog-api-client-go/api/<VERSION>/datadog"

If you’re a Java user, make sure you have the latest versions of Maven or Gradle before getting started here. In order for your client application to successfully interact with the Datadog API, you’ll need to configure it with a valid API key (for read access) and an application key (for write access). There are a few ways to do this, such as importing the keys as environment variables, as in the following Go example:

package main

import (
    "context"
    "fmt"
    "os"
    datadog "github.com/DataDog/datadog-api-client-go/api/v1/datadog"
)

func main() {
    ctx := context.WithValue(
        context.Background(),
        datadog.ContextAPIKeys,
        map[string]datadog.APIKey{
            "apiKeyAuth": {
                Key: os.Getenv("DD_CLIENT_API_KEY"),
            },
            "appKeyAuth": {
                Key: os.Getenv("DD_CLIENT_APP_KEY"),
            },

        },
    )
};

Then, you can validate your API key using the following:

    configuration := datadog.NewConfiguration()
    api_client := datadog.NewAPIClient(configuration)
    resp, r, err := api_client.AuthenticationApi.Validate(ctx).Execute()
    if err != nil {
        fmt.Fprintf(os.Stderr, "Error when calling `AuthenticationApi.Validate`: %v\n", err)
        fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r)
    }
    fmt.Fprintf(os.Stdout, "Response from `AuthenticationApi.Validate`: %v\n", resp)
}

Java and Go client libraries in action

Our client libraries enable you to interact with the Datadog API to perform a variety of actions. In the next few sections, we’ll go over some examples, including how to:

Retrieve and update dashboards

All of Datadog’s dashboards are available as JSON objects that you can retrieve and update programmatically. Each dashboard has a unique ID, which you’ll need to reference when sending a request. You can access a dashboard’s ID either from it’s URL path or from the id parameter of its JSON string. Once you have a dashboard’s ID, you can retrieve its JSON. For example, with the Go client library, you can use GetDashboard(), as in the following:

package main

import (
    "context"
    "fmt"
    "os"
    datadog "github.com/DataDog/datadog-api-client-go/api/v1/datadog"
)

func main() {
[...]
    dashboardId := "<DASHBOARD_ID>" 
    configuration := datadog.NewConfiguration()
    api_client := datadog.NewAPIClient(configuration)
    resp, r, err := api_client.DashboardsApi.GetDashboard(ctx, dashboardId).Execute()
    if err != nil {
        fmt.Fprintf(os.Stderr, "Error when calling `DashboardsApi.GetDashboard`: %v\n", err)
        fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r)
    }

    fmt.Fprintf(os.Stdout, "Response from `DashboardsApi.GetDashboard`: %v\n", resp)
}

You can also easily update a dashboard using UpdateDashboard() (or updateDashboard() in Java). For example, if you want to change a dashboard’s description or one of its timeseries widgets, you can modify the dashboard’s JSON. Then, simply include that dashboard’s ID and the updated JSON as arguments when you call the function.

Retrieve and search for metrics

Our client libraries enable you to send requests for a full list of metrics that are being actively reported to your Datadog account. Like dashboards, metrics are available via our API as JSON strings to make them easy to parse and read. If, for example, you’re interested in piping metrics from Datadog into your own data analysis workflows you can use the following Go code to request a full list of metrics using ListActiveMetrics():

package main

import (
    "context"
    "fmt"
    "os"
    datadog "github.com/DataDog/datadog-api-client-go/api/v1/datadog"
)

func main() {
[...]
    from := 900 
    host := "<EXAMPLE_HOST>" 
    configuration := datadog.NewConfiguration()
    api_client := datadog.NewAPIClient(configuration)
    resp, r, err := api_client.MetricsApi.ListActiveMetrics(ctx, from).Host(host).Execute()
    if err != nil {
        fmt.Fprintf(os.Stderr, "Error when calling `MetricsApi.ListActiveMetrics`: %v\n", err)
        fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r)
    }

    fmt.Fprintf(os.Stdout, "Response from `MetricsApi.ListActiveMetrics`: %v\n", resp)
}

Retrieve log data

Logs provide you with vital information about issues you may need to troubleshoot. With our client libraries, you can query Datadog’s API for logs using the same syntax as you would in the Log Explorer. For instance, if you want a list of error logs from a web service, you can use the LogsListRequest() function and include a query like "service:web* AND @http.status_code:[500 TO 599]" in your Go client library request as shown below:

package main

import (
    "context"
    "fmt"
    "os"
    datadog "github.com/DataDog/datadog-api-client-go/api/v1/datadog"
)
func main() {
[...]


    body := datadog.LogsListRequest{Index: "<EXAMPLE_INDEX>", Limit: 123, Query: "service:web* AND @http.status_code:[500 TO 599]", Sort: datadog.LogsSort{}, StartAt: "StartAt_example", Time: datadog.LogsListRequest_time{From: "2020-01-01 12:00:00
", Timezone: "UTC-4", To: "2020-02-01 12:00:00"}} 
    configuration := datadog.NewConfiguration()
    api_client := datadog.NewAPIClient(configuration)
    resp, r, err := api_client.LogsApi.ListLogs(ctx, body).Execute()
    if err != nil {
        fmt.Fprintf(os.Stderr, "Error when calling `LogsApi.ListLogs`: %v\n", err)
        fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r)
    }
    fmt.Fprintf(os.Stdout, "Response from `LogsApi.ListLogs`: %v\n", resp)
}

In addition to the query parameter, you must include a Time, or the timeframe to retrieve logs. For more information about these and other optional parameters, you can view our documentation.

It’s important to note that log lists have a maximum length of 1,000 logs, though you can reduce this with the limit parameter (123 in the example above). If your log list is longer than the limit, you’ll need to use our log pagination feature. This returns logs with a nextLogId parameter that you can use to query the next set of logs in your list (by including a startAt parameter in your next query set to the value returned in nextLogId).

More libraries, more possibilities

With these new client libraries for Java and Go, you can interact with Datadog’s API to programmatically execute tasks, helping you monitor data from over 800 integrations. While Java and Go libraries are currently our only two official API client libraries using the OpenAPI Specification, we will soon update our other API client libraries for languages like Python and Ruby so that they use the OpenAPI Specification as well, making them easy to adopt and contribute to.

If you have a Datadog account and would like to start using our client libraries, you can get a full list of them here. If you’re not already using Datadog, sign up today for a 14-day