Registry / observability / datadog-api-client

datadog-api-client

JSON →
library2.52.0pypypi✓ verified 49d ago

The `datadog-api-client` is the official Python client library for interacting with the Datadog API. It provides a structured, object-oriented interface to programmatically interact with all aspects of the Datadog platform, including metrics, monitors, events, and dashboards. The library is actively maintained with frequent minor releases, currently at version 2.52.0.

observabilityhttp-networking
pip install datadog-api-client
Install & Compatibility
Where this runs
tested against v2.55.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.950 runs
installs and imports cleanly · install 0.0s · import 0.387s · 86.8MB
glibc
py 3.103.950 runs
installs and imports cleanly · install 6.2s · import 0.344s · 87MB
86MB installed
● package 86MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

ApiClient
from datadog_api_client import ApiClient
Core class for making API requests, typically used with a Configuration object.
Configuration
from datadog_api_client import Configuration
Used to set up API keys, application keys, and other client settings.
MonitorsApi
from datadog_api_client.v1.api.monitors_api import MonitorsApi
Example of importing a specific API endpoint client from 'v1'. Note: Many 'v1' endpoints are deprecated.
MetricsApi
from datadog_api_client.v2.api.metrics_api import MetricsApi
Example of importing a specific API endpoint client from 'v2'. The 'v2' endpoints are generally preferred.
Monitor
from datadog_api_client.v1.model.monitor import Monitor
Example of importing a model schema for API request bodies. Specific models reside within versioned 'model' subpackages.
datadog
import datadog
This imports the *older* Datadog Python library, which is a separate package (pypi: `datadog`) and not `datadog-api-client`. Using this will result in different API methods and authentication.

This quickstart demonstrates how to authenticate with Datadog using API and Application keys (preferably from environment variables) and then create a new monitor using the `MonitorsApi` client. It also includes a comment for configuring regional endpoints.

import os from datadog_api_client import ApiClient, Configuration from datadog_api_client.v1.api.monitors_api import MonitorsApi from datadog_api_client.v1.model.monitor import Monitor from datadog_api_client.v1.model.monitor_type import MonitorType # Configure API keys, preferably via environment variables DD_API_KEY = os.environ.get('DD_API_KEY', '') DD_APP_KEY = os.environ.get('DD_APP_KEY', '') configuration = Configuration() configuration.api_key['apiKeyAuth'] = DD_API_KEY configuration.api_key['appKeyAuth'] = DD_APP_KEY # For non-US regions, set the site explicitly: # configuration.server_variables["site"] = "datadoghq.eu" # Example for EU site try: with ApiClient(configuration) as api_client: api_instance = MonitorsApi(api_client) # Create a basic monitor example body = Monitor( name="Example Monitor - Python Client", type=MonitorType("metric alert"), query="avg(system.cpu.user{host:"test-host"}) by {host} > 80", message="CPU usage is high! @pagerduty", tags=["env:dev", "team:backend"], priority=3, ) response = api_instance.create_monitor(body=body) print(f"Monitor created successfully: {response.name} (ID: {response.id})") except Exception as e: print(f"Error creating monitor: {e}")
Debug
Known issues
gotchaAlways use `DD_API_KEY` and `DD_APP_KEY` environment variables for authentication to avoid exposing credentials in code. While in-code configuration is possible, it is less secure.
fix
Store `DD_API_KEY` and `DD_APP_KEY` as environment variables. The client automatically picks them up, or you can explicitly set `configuration.api_key` from `os.environ.get()`.
affects: All versions
deprecatedMany V1 API endpoints are deprecated and have V2 equivalents. While V1 might still work, it's recommended to use V2 endpoints for new development and migrate existing code where possible to ensure access to the latest features and avoid future breaking changes.
fix
Consult the official Datadog API documentation to identify the V2 equivalent for your desired functionality and update your imports and API calls accordingly (e.g., `from datadog_api_client.v2.api.metrics_api import MetricsApi`).
affects: All versions, increasingly with new releases
gotchaThe default Datadog API site is `datadoghq.com` (US). If your Datadog account is hosted in a different region (e.g., EU, US1-FED), you must explicitly configure the client to use the correct regional endpoint. Otherwise, API calls will fail or target the wrong Datadog instance.
fix
Set the `DD_SITE` environment variable (e.g., `DD_SITE=datadoghq.eu`) or configure it in code: `configuration.server_variables["site"] = "datadoghq.eu"`.
affects: All versions
breakingThe client includes access to 'unstable' API endpoints that are subject to breaking changes without major version bumps. These endpoints require an explicit opt-in configuration step.
fix
Enable unstable operations with `configuration.unstable_operations["<OperationName>"] = True`. Be aware that code using these endpoints may break in future minor releases.
affects: All versions supporting unstable endpoints
gotchaDatadog APIs are subject to rate limits. Failing to implement retry and backoff logic can lead to API call failures (e.g., HTTP 429 Too Many Requests) and degraded application performance.
fix
Implement robust retry mechanisms with exponential backoff. The library can be configured with a custom retry policy using `urllib3.util.Retry`.
affects: All versions
gotchaThere are two distinct Python libraries for Datadog: `datadog` (the older client, `pip install datadog`) and `datadog-api-client` (the newer, generated client, `pip install datadog-api-client`). Ensure you are importing and using the correct library for your needs, as they have different interfaces and capabilities. `datadog-api-client` supports all public Datadog API endpoints.
fix
For comprehensive API coverage and the latest features, use `datadog-api-client`. If you are migrating, be aware of the different import paths and API call patterns.
affects: All versions
gotchaThere have been reports of memory not being released after API calls, potentially leading to increased memory usage in long-running applications.
fix
Ensure `ApiClient` is used as a context manager (`with ApiClient(...) as api_client:`), which handles connection closing. For persistent issues, consider explicitly calling garbage collection (`gc.collect()`) after intensive API operations or analyzing memory usage patterns.
affects: Potentially all 2.x versions
gotchaWhen constructing API parameters like Datadog query strings, which often contain special characters (e.g., quotes, curly braces), ensure proper Python string literal syntax. Unescaped quotes within a string literal can lead to `SyntaxError` before the API call is even made, preventing your script from running.
fix
Correct the string literal by using consistent outer quotes (single or double) and escaping any inner quotes that match the outer ones (e.g., `query='avg(system.cpu.user{host:"test-host"}) by {host} > 80'`). Alternatively, use triple quotes (single or double) to define strings that can contain both single and double quotes without explicit escaping (e.g., `query="""avg(system.cpu.user{host:"test-host"}) by {host} > 80"""`).
affects: All versions (Python syntax issue)
breakingA `SyntaxError: invalid syntax` can occur when constructing query strings that contain nested quotes (e.g., `{host:"test-host"}`). Python's string literal rules interpret the inner quote prematurely as the end of the string, leading to unparsable code.
fix
To resolve `SyntaxError` with nested quotes, use different quote types for the outer string and the inner content (e.g., `query='avg(system.cpu.user{host:"test-host"}) by {host} > 80'`), or escape the inner quotes (e.g., `query="avg(system.cpu.user{host:\"test-host\"}) by {host} > 80"`). For Python 3.6+, f-strings can also be used with careful escaping of literal curly braces (e.g., `query=f"avg(system.cpu.user{{host:\"test-host\"}}) by {{host}} > 80"`).
affects: All versions of `datadog-api-client` when constructing query strings with nested quotes.
Errors
Common errors & fixes
datadog_api_client.exceptions.UnauthorizedException
This error occurs when the Datadog API Key and/or Application Key are either missing, incorrect, or do not have the necessary permissions for the requested API operation.
fix
Ensure you have set the `DD_API_KEY` and `DD_APP_KEY` environment variables with valid keys, or explicitly configure them in your `Configuration` object:

```python
from datadog_api_client import Configuration, ApiClient

configuration = Configuration()
configuration.api_key['apiKeyAuth'] = 'YOUR_DATADOG_API_KEY'
configuration.api_key['appKeyAuth'] = 'YOUR_DATADOG_APP_KEY'

# Or, relying on environment variables (default behavior)
# configuration = Configuration()

with ApiClient(configuration) as api_client:
    # Your API calls here
    pass
```
ModuleNotFoundError: No module named 'datadog_api_client'
The `datadog-api-client` library is not installed in your current Python environment, or the environment where your script is running does not have access to the installed package.
fix
Install the library using pip:

```bash
pip install datadog-api-client
```

If you need async support, install with the `async` extra:

```bash
pip install datadog-api-client[async]
```
datadog_api_client.exceptions.ApiTypeError
This exception is raised when the arguments provided to an API method do not match the expected data types or structure defined by the API specification, often due to missing required fields or incorrect parameter types for complex objects.
fix
Review the official `datadog-api-client` documentation for the specific API endpoint and model you are using. Ensure all required parameters are supplied and that their values adhere to the expected data types and formats (e.g., providing a string where an enum is expected, or missing a required field in a body object). For example:

```python
from datadog_api_client.v1.model.monitor import Monitor
from datadog_api_client.v1.model.monitor_type import MonitorType

# Ensure all required fields for Monitor are present and correctly typed
body = Monitor(
    name="My Example Monitor",
    type=MonitorType("metric alert"), # Correct enum usage
    query='avg(system.cpu.user{host:my-host}) > 0.5',
    message="Alert message @pagerduty",
    tags=["env:prod", "team:backend"],
    priority=3,
    # Other optional but correctly typed fields
)
```
Upgrade
Version history
2.55.0latest on PyPI
Audit
Dependencies
PythonrequiredRequired for library execution.
asyncoptionalOptional extra for asynchronous operations via AsyncApiClient.
urllib3requiredUnderpins HTTP requests; custom retry policies can be based on it.
Agent activity
70 hits · last 30 days
node
4
ahrefsbot
3
seranking-bot
3
mj12bot
1
amazonbot
1
googlebot
1
Resources