### Installation and Initialization Source: https://context7.com/datadog/datadogpy/llms.txt Instructions on how to install and initialize the Datadog Python library with API credentials and DogStatsD client configuration. ```APIDOC ## Installation and Initialization Initialize the Datadog library with API credentials and configure the DogStatsD client for metric collection. ```python from datadog import initialize, api, statsd # Method 1: Explicit initialization with credentials options = { "api_key": "your_api_key_here", "app_key": "your_app_key_here", "api_host": "https://api.datadoghq.com", # Optional, defaults to US "statsd_host": "127.0.0.1", "statsd_port": 8125, "statsd_namespace": "myapp", "statsd_constant_tags": ["env:production", "service:web"], } initialize(**options) # Method 2: Environment variable initialization # Set DATADOG_API_KEY, DATADOG_APP_KEY (or DD_API_KEY, DD_APP_KEY) # Then simply call: initialize() # Method 3: Initialize with Unix Domain Socket (UDS) options = { "api_key": "your_api_key_here", "statsd_socket_path": "/var/run/datadog/dsd.socket", } initialize(**options) ``` ``` -------------------------------- ### Install Datadog Python Library Source: https://github.com/datadog/datadogpy/blob/master/doc/source/index.md Install the Datadog Python library using pip. ```default pip install datadog ``` -------------------------------- ### Install Project in Editable Mode Source: https://github.com/datadog/datadogpy/blob/master/DEVELOPMENT.md Install the project locally in editable mode using pip, allowing for direct changes and manual testing. Replace `` with the actual path to your cloned repository. ```bash pip install -e ``` -------------------------------- ### Setup Integration Test Environment Variables Source: https://github.com/datadog/datadogpy/blob/master/DEVELOPMENT.md Export these environment variables to configure the integration tests. WARNING: Use keys for a testing organization only, as these tests perform destructive changes. ```bash # !!!WARNING!!! The integration tests will use these keys to do destructive changes. # Never use keys for an organization that contains anything important. export DD_TEST_CLIENT_API_KEY= export DD_TEST_CLIENT_APP_KEY= export DD_TEST_CLIENT_USER= ``` -------------------------------- ### Create, Get, Update, Mute, Unmute, List, Validate, and Delete Monitors Source: https://context7.com/datadog/datadogpy/llms.txt Demonstrates the full lifecycle management of Datadog monitors, including creation with various options, retrieval, updates, muting/unmuting, listing with filters, validation, and deletion. ```python from datadog import initialize, api initialize(api_key="your_api_key", app_key="your_app_key") # Create a metric threshold monitor monitor = api.Monitor.create( type="metric alert", query="avg(last_5m):avg:system.cpu.user{*}" "> 90", name="High CPU Usage Alert", message="CPU usage is above 90%!\n\nHost: {{host.name}}\nValue: {{value}}\n\n@slack-alerts @pagerduty", tags=["team:infrastructure", "severity:high"], options={ "thresholds": { "critical": 90, "warning": 80, }, "notify_no_data": True, "no_data_timeframe": 10, "renotify_interval": 60, "escalation_message": "CPU still high after 1 hour! @oncall-team", "include_tags": True, } ) print(f"Monitor created with ID: {monitor['id']}") # Get monitor details monitor_details = api.Monitor.get(monitor['id'], group_states=["alert", "warn"]) print(f"Monitor status: {monitor_details['overall_state']}") # Update monitor api.Monitor.update( monitor['id'], query="avg(last_5m):avg:system.cpu.user{*}" "> 85", options={"thresholds": {"critical": 85, "warning": 75}} ) # Mute a monitor api.Monitor.mute(monitor['id'], scope="host:web-server-01", end=int(time.time()) + 3600) # Unmute a monitor api.Monitor.unmute(monitor['id'], scope="host:web-server-01") # List all monitors with filters monitors = api.Monitor.get_all( tags=["team:infrastructure"], monitor_tags=["severity:high"] ) for m in monitors: print(f"Monitor: {m['name']} - State: {m['overall_state']}") # Validate monitor definition before creating validation = api.Monitor.validate( type="metric alert", query="avg(last_5m):avg:system.cpu.user{*}" "> 90" ) print(f"Validation result: {validation}") # Delete monitor api.Monitor.delete(monitor['id']) ``` -------------------------------- ### Run Datadog Python Client Benchmarks Source: https://github.com/datadog/datadogpy/blob/master/README.md Execute local benchmarks to assess the DogStatsD library's throughput. Ensure `psutil` is installed. Customize runs using `BENCHMARK_*` environment variables. ```sh $ # Python 2 Example $ python2 -m unittest -vvv tests.performance.test_statsd_throughput ``` ```sh $ # Python 3 Example $ python3 -m unittest -vvv tests.performance.test_statsd_throughput ``` ```sh $ # Example #1 $ BENCHMARK_NUM_RUNS=10 BENCHMARK_NUM_THREADS=1 BENCHMARK_NUM_DATAPOINTS=5000 BENCHMARK_TRANSPORT="UDP" python2 -m unittest -vvv tests.performance.test_statsd_throughput ``` ```sh $ # Example #2 $ BENCHMARK_NUM_THREADS=10 BENCHMARK_TRANSPORT="UDS" python3 -m unittest -vvv tests.performance.test_statsd_throughput ``` -------------------------------- ### Get All Hosts with Metadata Source: https://context7.com/datadog/datadogpy/llms.txt Retrieve a list of all hosts with their metadata, filtered by environment and including muted host data. Limited to 1000 results. ```python all_hosts = api.Hosts.get_all( filter="env:production", include_hosts_metadata=True, include_muted_hosts_data=True, count=1000 ) ``` -------------------------------- ### Create, Get, Update, List, and Delete Dashboards Source: https://context7.com/datadog/datadogpy/llms.txt Shows how to programmatically create, retrieve, modify, list, and delete Datadog dashboards, including defining widgets and template variables. ```python from datadog import initialize, api initialize(api_key="your_api_key", app_key="your_app_key") # Create a dashboard with multiple widgets dashboard = api.Dashboard.create( title="Application Overview", description="Real-time application metrics and health status", widgets=[ { "definition": { "type": "timeseries", "title": "Request Rate", "requests": [ { "q": "sum:myapp.requests.count{*}.as_rate()", "display_type": "line" } ] } }, { "definition": { "type": "query_value", "title": "Active Users", "requests": [{"q": "avg:myapp.active_users{*}"}], "precision": 0 } }, { "definition": { "type": "toplist", "title": "Top Endpoints by Latency", "requests": [ { "q": "top(avg:myapp.response_time{*} by {endpoint}, 10, 'mean', 'desc')" } ] } } ], layout_type="ordered", is_read_only=False, notify_list=["user@example.com"], template_variables=[ {"name": "env", "default": "production", "prefix": "environment"} ] ) print(f"Dashboard created: {dashboard['url']}") # Get dashboard by ID dashboard_details = api.Dashboard.get(dashboard['id']) # Update dashboard api.Dashboard.update( dashboard['id'], title="Application Overview v2", widgets=dashboard_details['widgets'], layout_type="ordered" ) # List all dashboards dashboards = api.Dashboard.get_all() for d in dashboards.get('dashboards', []): print(f"Dashboard: {d['title']} - ID: {d['id']}") # Delete dashboard api.Dashboard.delete(dashboard['id']) ``` -------------------------------- ### Get Host Totals Source: https://context7.com/datadog/datadogpy/llms.txt Retrieve the total count of active hosts and the number of hosts that are currently up. ```python # Get host totals totals = api.Hosts.totals() print(f"Total hosts: {totals['total_active']}, Up: {totals['total_up']}") ``` -------------------------------- ### Get Tags for a Host Source: https://context7.com/datadog/datadogpy/llms.txt Retrieve all tags associated with a specific host. ```python # Get tags for a host host_tags = api.Tag.get("web-server-01") print(f"Tags: {host_tags['tags']}") ``` -------------------------------- ### Schedule a Downtime Source: https://context7.com/datadog/datadogpy/llms.txt Schedule a downtime for a specific scope with a start and end time. Monitors within the scope will be silenced. Supports monitor tags and timezones. ```python # Schedule a downtime downtime = api.Downtime.create( scope="host:web-server-01", start=now, end=now + 7200, # 2 hours message="Scheduled maintenance window", monitor_tags=["team:infrastructure"], timezone="America/New_York" ) print(f"Downtime scheduled: {downtime['id']}") ``` -------------------------------- ### Build Package Locally Source: https://github.com/datadog/datadogpy/blob/master/RELEASING.md Build the package locally using setup.py sdist. This is a prerequisite for testing changes in a fresh virtual environment. ```bash python3 setup.py sdist ``` -------------------------------- ### Initialize Datadog Client Source: https://github.com/datadog/datadogpy/blob/master/doc/source/index.md Initialize the Datadog client with API and App keys, and configure statsd host and port. ```default from datadog import initialize initialize( api_key="", app_key="", statsd_host="127.0.0.1", statsd_port=8125 ) ``` -------------------------------- ### Get Downtime Details Source: https://context7.com/datadog/datadogpy/llms.txt Retrieve detailed information about a specific downtime by its ID. ```python # Get downtime details downtime_details = api.Downtime.get(downtime['id']) ``` -------------------------------- ### Initialize and Use DogStatsd Client Source: https://github.com/datadog/datadogpy/blob/master/doc/source/index.md Instantiate and use the DogStatsd client to submit metrics to the Agent. ```default from datadog.dogstatsd import DogStatsd client = DogStatsd() client.increment("home.page.hits") ``` -------------------------------- ### Update Downtime Source: https://context7.com/datadog/datadogpy/llms.txt Modify an existing downtime by its ID, for example, to extend its duration or change the message. ```python # Update downtime api.Downtime.update( downtime['id'], end=now + 14400, # Extend to 4 hours message="Extended maintenance window" ) ``` -------------------------------- ### Initialize Datadog API Client with Keys Source: https://github.com/datadog/datadogpy/blob/master/README.md Initialize the Datadog API client using your API and application keys. Ensure these keys are kept secure. ```python from datadog import initialize, api options = { "api_key": "", "app_key": "", } initialize(**options) title = "Something big happened!" text = "And let me tell you all about it here!" tags = ["version:1", "application:web"] api.Event.create(title=title, text=text, tags=tags) ``` -------------------------------- ### Initialize and Use ThreadStats Client Source: https://github.com/datadog/datadogpy/blob/master/doc/source/index.md Initialize the library and create a ThreadStats instance to submit metrics in a worker thread. ```default from datadog.threadstats import ThreadStats statsd = ThreadStats() statsd.start() # Creates a worker thread used to submit metrics. # Use statsd just like any other DatadogStatsd client. statsd.increment("home.page.hits") ``` -------------------------------- ### Initialize DogStatsd with Aggregation Source: https://context7.com/datadog/datadogpy/llms.txt Use initialize() or create a custom DogStatsd client to enable client-side aggregation. Configure flush intervals and sample limits for efficient metric handling. Aggregated metrics are sent automatically or can be flushed manually. ```python initialize( statsd_host="127.0.0.1", statsd_port=8125, statsd_disable_aggregation=False, # Enable aggregation statsd_aggregation_flush_interval=0.3, # Flush every 300ms ) ``` ```python client = DogStatsd( host="127.0.0.1", port=8125, disable_aggregation=False, flush_interval=0.5, # 500ms flush interval max_metric_samples_per_context=100, # Limit samples per metric context ) # Metrics are now aggregated client-side before sending for i in range(10000): client.increment("high_volume.counter") client.gauge("high_volume.gauge", i % 100) # Manually flush aggregated metrics client.flush_aggregated_metrics() # Enable/disable aggregation at runtime statsd.enable_aggregation(flush_interval=0.3) statsd.disable_aggregation() # Clean shutdown client.stop() ``` -------------------------------- ### Initialize Datadog API Client with Environment Variables Source: https://github.com/datadog/datadogpy/blob/master/README.md Initialize the Datadog API client automatically by setting environment variables `DD_API_KEY` and `DD_APP_KEY`. This method is convenient for deployment environments. ```python from datadog import initialize, api # Assuming you've set `DD_API_KEY` and `DD_APP_KEY` in your env, # initialize() will pick it up automatically initialize() title = "Something big happened!" text = "And let me tell you all about it here!" tags = ["version:1", "application:web"] api.Event.create(title=title, text=text, tags=tags) ``` -------------------------------- ### Initialize Datadog Library Source: https://context7.com/datadog/datadogpy/llms.txt Initialize the Datadog library with API credentials and configure the DogStatsD client. Supports explicit initialization, environment variables, or Unix Domain Socket (UDS). ```python from datadog import initialize, api, statsd # Method 1: Explicit initialization with credentials options = { "api_key": "your_api_key_here", "app_key": "your_app_key_here", "api_host": "https://api.datadoghq.com", # Optional, defaults to US "statsd_host": "127.0.0.1", "statsd_port": 8125, "statsd_namespace": "myapp", "statsd_constant_tags": ["env:production", "service:web"], } initialize(**options) # Method 2: Environment variable initialization # Set DATADOG_API_KEY, DATADOG_APP_KEY (or DD_API_KEY, DD_APP_KEY) # Then simply call: initialize() # Method 3: Initialize with Unix Domain Socket (UDS) options = { "api_key": "your_api_key_here", "statsd_socket_path": "/var/run/datadog/dsd.socket", } initialize(**options) ``` -------------------------------- ### Instantiate DogStatsD Client with UDP Source: https://github.com/datadog/datadogpy/blob/master/README.md Instantiate the DogStatsD client using UDP. Ensure the Datadog Agent is running and available on the specified host and port. ```python from datadog import initialize, statsd options = { "statsd_host": "127.0.0.1", "statsd_port": 8125, } initialize(**options) ``` -------------------------------- ### Configure Datadog Library with Environment Variables Source: https://context7.com/datadog/datadogpy/llms.txt Configure the Datadog library using environment variables for API keys, host, DogStatsD settings, global tags, and origin detection. This is ideal for containerized deployments. ```python import os # API Configuration os.environ["DATADOG_API_KEY"] = "your_api_key" os.environ["DATADOG_APP_KEY"] = "your_app_key" os.environ["DATADOG_HOST"] = "https://api.datadoghq.com" # Alternative DD_ prefix (APM-style) os.environ["DD_API_KEY"] = "your_api_key" os.environ["DD_APP_KEY"] = "your_app_key" # DogStatsD Configuration os.environ["DD_AGENT_HOST"] = "127.0.0.1" os.environ["DD_DOGSTATSD_PORT"] = "8125" # Global tags for all metrics os.environ["DATADOG_TAGS"] = "env:production,service:myapp,version:1.0" os.environ["DD_ENV"] = "production" os.environ["DD_SERVICE"] = "myapp" os.environ["DD_VERSION"] = "1.0.0" # Origin detection (for container environments) os.environ["DD_ENTITY_ID"] = "pod_uid_here" os.environ["DD_ORIGIN_DETECTION_ENABLED"] = "true" # Disable metrics collection (useful for local development) os.environ["DD_DOGSTATSD_DISABLE"] = "false" from datadog import initialize, statsd # Initialize will pick up environment variables automatically initialize() # Metrics will include env, service, version tags automatically statsd.increment("requests.count") ``` -------------------------------- ### Run Unit Tests with Python 3.7 Source: https://github.com/datadog/datadogpy/blob/master/DEVELOPMENT.md Execute unit tests specifically for the Python 3.7 environment using tox. ```bash tox -e py37 ``` -------------------------------- ### Bump Version to Development Source: https://github.com/datadog/datadogpy/blob/master/RELEASING.md After releasing, bump the version in datadog/version.py to a development version (e.g., appending '.dev'). This prepares the project for future development. ```python VERSION = "0.34.1.dev" ``` -------------------------------- ### Use Global DogStatsd Instance Source: https://github.com/datadog/datadogpy/blob/master/doc/source/index.md Initialize the library and use the global statsd instance to increment a metric. ```default >>> from datadog import initialize, statsd >>> initialize(statsd_host="localhost", statsd_port=8125) >>> statsd.increment("home.page.hits") ``` -------------------------------- ### Clone Datadogpy Repository Source: https://github.com/datadog/datadogpy/blob/master/DEVELOPMENT.md Instructions for forking and cloning the datadogpy repository for development. ```bash git clone git@github.com:your-username/datadogpy.git ``` -------------------------------- ### Send Gauge Metrics with DogStatsD Source: https://context7.com/datadog/datadogpy/llms.txt Illustrates how to send gauge metrics using DogStatsD, including basic usage, adding tags, specifying sample rates, and including timestamps for older agent versions. ```python from datadog import initialize, statsd initialize(statsd_host="127.0.0.1", statsd_port=8125) # Basic gauge - current value of something statsd.gauge("myapp.queue.size", 42) # Gauge with tags statsd.gauge("myapp.memory.used_mb", 1024, tags=["host:web-01", "region:us-east"]) # Gauge with sample rate (send only 50% of metrics) statsd.gauge("myapp.cache.hit_ratio", 0.85, sample_rate=0.5) # Gauge with timestamp (requires Datadog Agent 7.40.0+) import time statsd.gauge_with_timestamp( "myapp.batch.processed", 1500, timestamp=int(time.time()) - 300, # 5 minutes ago tags=["job:daily_sync"] ) ``` -------------------------------- ### Show Changes for Release Source: https://github.com/datadog/datadogpy/blob/master/RELEASING.md View changes ready for release using the ddev release show changes command. Ensure all necessary labels are applied to PRs. ```bash ddev release show changes . ``` -------------------------------- ### List All Tags Source: https://context7.com/datadog/datadogpy/llms.txt Retrieve a dictionary of all tags across all hosts. The keys are hostnames and values are lists of tags. ```python # List all tags all_tags = api.Tag.get_all() for host, tags in all_tags.get("tags", {}).items(): print(f"{host}: {tags}") ``` -------------------------------- ### Environment Variables Configuration Source: https://context7.com/datadog/datadogpy/llms.txt Configure the Datadog library using environment variables for containerized deployments. ```APIDOC ## Environment Variables Configuration ### Description Configure the Datadog library using environment variables for containerized deployments. ### Environment Variables - **DATADOG_API_KEY**: Your Datadog API key. - **DATADOG_APP_KEY**: Your Datadog application key. - **DATADOG_HOST**: The Datadog API endpoint (e.g., `https://api.datadoghq.com`). - **DD_API_KEY**: Alternative for API key (APM-style). - **DD_APP_KEY**: Alternative for application key (APM-style). - **DD_AGENT_HOST**: Hostname for DogStatsD. - **DD_DOGSTATSD_PORT**: Port for DogStatsD. - **DATADOG_TAGS**: Global tags for all metrics (comma-separated). - **DD_ENV**: Environment tag. - **DD_SERVICE**: Service tag. - **DD_VERSION**: Version tag. - **DD_ENTITY_ID**: Entity ID for origin detection. - **DD_ORIGIN_DETECTION_ENABLED**: Enable origin detection. - **DD_DOGSTATSD_DISABLE**: Disable DogStatsD collection. ``` -------------------------------- ### Manage Datadog Hosts with API Source: https://context7.com/datadog/datadogpy/llms.txt Manage host muting and retrieve host information using the Datadog API. Ensure API credentials are initialized. Muting can be overridden. ```python from datadog import initialize, api import time initialize(api_key="your_api_key", app_key="your_app_key") # Mute a host api.Host.mute( "web-server-01", end=int(time.time()) + 3600, # Mute for 1 hour message="Maintenance window", override=True # Override existing mute ) # Unmute a host api.Host.unmute("web-server-01") # Search for hosts hosts = api.Hosts.search( filter="web", sort_field="cpu", sort_dir="desc", count=100 ) for host in hosts.get("host_list", []): print(f"Host: {host['name']} - CPU: {host.get('metrics', {}).get('cpu')}") ``` -------------------------------- ### Instantiate DogStatsD Client with UDS Source: https://github.com/datadog/datadogpy/blob/master/README.md Instantiate the DogStatsD client using Unix Domain Sockets (UDS). This method requires specifying the socket path. ```python from datadog import initialize, statsd options = { "statsd_socket_path": PATH_TO_SOCKET, } initialize(**options) ``` -------------------------------- ### Run All Tests in 'dogstatsd' Folder Source: https://github.com/datadog/datadogpy/blob/master/DEVELOPMENT.md Execute all tests within the `tests/unit/dogstatsd` directory by specifying the path directly in the tox command. ```bash tox -- tests/unit/dogstatsd ``` -------------------------------- ### Run Admin Integration Tests Source: https://github.com/datadog/datadogpy/blob/master/DEVELOPMENT.md Explicitly run integration tests that require admin privileges or perform destructive actions. Ensure you understand the risks before running. ```bash tox -e integration-admin ``` -------------------------------- ### Run Regular Integration Tests Source: https://github.com/datadog/datadogpy/blob/master/DEVELOPMENT.md Execute standard integration tests that do not require admin privileges. These tests create and clean up Datadog resources. ```bash tox -e integration ``` -------------------------------- ### Batch Metrics with DogStatsd Context Manager Source: https://context7.com/datadog/datadogpy/llms.txt Use the context manager to batch multiple metrics together for efficient transmission. Metrics are sent when exiting the `with statsd:` block or by explicitly calling `close_buffer()`. ```python from datadog import initialize, statsd initialize(statsd_host="127.0.0.1", statsd_port=8125) # Batch multiple metrics together with statsd: statsd.gauge("myapp.users.online", 1523) statsd.gauge("myapp.users.active", 892) statsd.increment("myapp.requests.total", 150) statsd.histogram("myapp.response.time", 125) statsd.distribution("myapp.payment.amount", 49.99) # All metrics are sent in a single packet when exiting the context # Using open_buffer/close_buffer explicitly statsd.open_buffer() try: for i in range(100): statsd.increment("myapp.batch.items", tags=[f"batch_id:{i}"]) finally: statsd.close_buffer() # Flushes all buffered metrics ``` -------------------------------- ### Tagging API Source: https://context7.com/datadog/datadogpy/llms.txt Manage tags on hosts for organizing and filtering your infrastructure. ```APIDOC ## api.Tag ### Description Manage tags on hosts for organizing and filtering your infrastructure. ### Methods #### Add tags to a host ##### Endpoint `POST /api/v1/tags/{host}` (Implicitly called by `api.Tag.create`) ##### Parameters - **host** (string) - Required - The hostname to add tags to. - **tags** (list of strings) - Required - A list of tags to add. - **source** (string) - Optional - The source of the tags. ### Get tags for a host ##### Endpoint `GET /api/v1/tags/{host}` (Implicitly called by `api.Tag.get`) ##### Parameters - **host** (string) - Required - The hostname to retrieve tags for. ##### Response Example ```json { "tags": ["env:production", "team:platform"] } ``` ### Update all tags for a host ##### Endpoint `PUT /api/v1/tags/{host}` (Implicitly called by `api.Tag.update`) ##### Parameters - **host** (string) - Required - The hostname to update tags for. - **tags** (list of strings) - Required - A list of tags to set for the host. - **source** (string) - Optional - The source of the tags. ### List all tags ##### Endpoint `GET /api/v1/tags` (Implicitly called by `api.Tag.get_all`) ##### Response Example ```json { "tags": { "web-server-01": ["env:production", "team:platform"], "db-server-01": ["env:staging"] } } ``` ### Delete tags from a host ##### Endpoint `DELETE /api/v1/tags/{host}` (Implicitly called by `api.Tag.delete`) ##### Parameters - **host** (string) - Required - The hostname to remove tags from. *Note: This method deletes all tags associated with the host.* ``` -------------------------------- ### POST /api/v1/series Source: https://context7.com/datadog/datadogpy/llms.txt Submit custom metrics to Datadog for tracking application performance, business KPIs, and system health. ```APIDOC ## POST /api/v1/series ### Description Submit custom metrics to Datadog for tracking application performance, business KPIs, and system health. ### Method POST ### Endpoint /api/v1/series ### Parameters #### Query Parameters - **api_key** (string) - Required - Your Datadog API key. - **application_key** (string) - Required - Your Datadog Application key. #### Request Body - **metric** (string) - Required - The name of the metric. - **points** (array of arrays) - Required - An array of points, where each point is a tuple of `(timestamp, value)`. - **type** (string) - Optional - The type of the metric. Can be 'count', 'gauge', 'rate', or ' விகிதம்'. Defaults to 'gauge'. - **tags** (array of strings) - Optional - Tags to apply to the metric. - **host** (string) - Optional - The host associated with the metric. - **interval** (integer) - Optional - The interval in seconds for the metric. ### Request Example ```json { "metric": "myapp.requests.count", "points": [["1678886400", 150]], "type": "count", "tags": ["endpoint:/api/users", "method:GET"], "host": "web-server-01" } ``` ### Response #### Success Response (200) - **status** (string) - Indicates the status of the submission (e.g., 'ok'). #### Response Example ```json { "status": "ok" } ``` ## GET /api/v1/query ### Description Query metrics within a specified time range using Datadog's query language. ### Method GET ### Endpoint /api/v1/query ### Parameters #### Query Parameters - **api_key** (string) - Required - Your Datadog API key. - **application_key** (string) - Required - Your Datadog Application key. - **start** (integer) - Required - The start of the time range in epoch seconds. - **end** (integer) - Required - The end of the time range in epoch seconds. - **query** (string) - Required - The Datadog query string (e.g., 'avg:myapp.response_time{*}'). ### Response #### Success Response (200) - **results** (array of objects) - The results of the metric query. #### Response Example ```json { "results": [ { "metric": "myapp.response_time", "points": [[1678886400, 245.5]] } ] } ``` ``` -------------------------------- ### DogStatsd Context Manager for Batching Source: https://context7.com/datadog/datadogpy/llms.txt Use the context manager to batch multiple metrics together for efficient transmission. ```APIDOC ## DogStatsd Context Manager for Batching ### Description Use the context manager to batch multiple metrics together for efficient transmission. ### Method POST (implied, as it sends data) ### Endpoint /api/v1/series (implied, for metric submission) ### Parameters (No direct parameters for the context manager itself, but underlying statsd methods apply) ### Request Example ```python from datadog import initialize, statsd initialize(statsd_host="127.0.0.1", statsd_port=8125) with statsd: statsd.gauge("myapp.users.online", 1523) statsd.gauge("myapp.users.active", 892) statsd.increment("myapp.requests.total", 150) statsd.histogram("myapp.response.time", 125) statsd.distribution("myapp.payment.amount", 49.99) # Explicit buffer management statsd.open_buffer() try: for i in range(100): statsd.increment("myapp.batch.items", tags=[f"batch_id:{i}"]) finally: statsd.close_buffer() ``` ### Response #### Success Response (200) An empty response body indicates success for the batch submission. #### Response Example (No response body for success) ``` -------------------------------- ### Generate Changelog Source: https://github.com/datadog/datadogpy/blob/master/RELEASING.md Update the CHANGELOG.md file by running the ddev release changelog command with the new version number. This should be done at the root of the project. ```bash ddev release changelog . ``` -------------------------------- ### api.Host and api.Hosts Source: https://context7.com/datadog/datadogpy/llms.txt Manage host muting and retrieve host information. ```APIDOC ## api.Host and api.Hosts ### Description Manage host muting and retrieve host information. ### Method - Mute: PUT - Unmute: DELETE - Search: GET ### Endpoint - Mute/Unmute: /api/v1/mute/:host_id - Search: /api/v1/hosts ### Parameters #### api.Host.mute Parameters - **host_name** (string) - Required - The name of the host to mute. - **end** (integer) - Required - The Unix timestamp when the mute should end. - **message** (string) - Optional - A message explaining the reason for muting. - **override** (boolean) - Optional - Whether to override an existing mute. #### api.Host.unmute Parameters - **host_name** (string) - Required - The name of the host to unmute. #### api.Hosts.search Parameters - **filter** (string) - Optional - A filter string to search for hosts. - **sort_field** (string) - Optional - The field to sort the results by. - **sort_dir** (string) - Optional - The direction of the sort ('asc' or 'desc'). - **count** (integer) - Optional - The maximum number of results to return. - **start** (integer) - Optional - The index of the first result to return. ### Request Example ```python from datadog import initialize, api import time initialize(api_key="your_api_key", app_key="your_app_key") # Mute a host api.Host.mute( "web-server-01", end=int(time.time()) + 3600, message="Maintenance window", override=True ) # Unmute a host api.Host.unmute("web-server-01") # Search for hosts hosts = api.Hosts.search( filter="web", sort_field="cpu", sort_dir="desc", count=100 ) for host in hosts.get("host_list", []): print(f"Host: {host['name']} - CPU: {host.get('metrics', {}).get('cpu')}") ``` ### Response #### Success Response (200) - **mute/unmute**: An empty response body indicates success. - **search**: A JSON object containing a list of hosts and their details. #### Response Example (Search) ```json { "host_list": [ { "name": "web-server-01", "metrics": { "cpu": 50.5 } } ] } ``` ``` -------------------------------- ### High-Performance Metrics with ThreadStats Source: https://context7.com/datadog/datadogpy/llms.txt Use ThreadStats for collecting application metrics with automatic background flushing. Ensure API credentials are initialized. Metrics are thread-safe. ```python from datadog import initialize, ThreadStats import time # Initialize API credentials initialize(api_key="your_api_key", app_key="your_app_key") # Create ThreadStats instance stats = ThreadStats( namespace="myapp", constant_tags=["env:production", "service:web"] ) # Start with background thread flushing (default) stats.start( flush_interval=10, # Flush every 10 seconds roll_up_interval=10, # Aggregate metrics over 10 second windows flush_in_thread=True # Use background thread ) # Record metrics (thread-safe) stats.increment("page.views") stats.increment("api.requests", tags=["endpoint:/users"]) stats.gauge("memory.usage", 1024) stats.histogram("request.latency", 125.5) stats.distribution("payment.amount", 99.99) stats.set("unique.visitors", "user_12345") # Decrement counter stats.decrement("queue.pending", value=5) # Using the timer context manager def process_request(): with stats.timer("request.process_time"): time.sleep(0.1) return {"status": "ok"} # Using the timed decorator @stats.timed("db.query_time", tags=["query:select"]) def query_database(query): time.sleep(0.05) return [] # Send an event stats.event( title="Feature Flag Enabled", message="Enabled dark mode feature for 10% of users", alert_type="info", tags=["feature:dark_mode"] ) # Manual flush (blocking call) stats.flush() # Stop ThreadStats when shutting down stats.stop() ``` -------------------------------- ### Run Flake8 Style Checks Source: https://github.com/datadog/datadogpy/blob/master/DEVELOPMENT.md Validate code style using Flake8 by running the dedicated tox environment. ```bash tox -e flake8 ``` -------------------------------- ### Record Timing Metrics Source: https://context7.com/datadog/datadogpy/llms.txt Use `statsd.timing` to record the duration of operations in milliseconds. This can be done by providing a direct value or by manually measuring the elapsed time. Tags can be added to categorize timings. ```python from datadog import initialize, statsd import time initialize(statsd_host="127.0.0.1", statsd_port=8125) # Record a timing value directly (in milliseconds) statsd.timing("myapp.query.duration", 75) # Manual timing measurement start = time.time() # ... perform some operation ... elapsed_ms = (time.time() - start) * 1000 statsd.timing("myapp.operation.duration", elapsed_ms, tags=["operation:sync"]) ``` -------------------------------- ### Send Distribution Metrics Source: https://context7.com/datadog/datadogpy/llms.txt Use `statsd.distribution` to send metrics for global statistical aggregation across your fleet. This is useful for metrics like response times or payment amounts where percentiles across all hosts are important. Tags can be included. ```python from datadog import initialize, statsd initialize(statsd_host="127.0.0.1", statsd_port=8125) # Track response times as distribution statsd.distribution("myapp.response.time", 125.5) # Distribution with tags statsd.distribution( "myapp.payment.amount", 99.99, tags=["currency:USD", "payment_method:credit_card"] ) # Track percentiles across all hosts statsd.distribution( "myapp.page.load_time", 2345, # milliseconds tags=["page:/checkout", "browser:chrome"] ) ``` -------------------------------- ### Monitor API Source: https://context7.com/datadog/datadogpy/llms.txt Create, manage, and interact with Datadog monitors. ```APIDOC ## api.Monitor.create ### Description Create and manage monitors to alert on metrics, logs, or other data sources. ### Method POST ### Endpoint /api/v1/monitor ### Parameters #### Request Body - **type** (string) - Required - The type of monitor (e.g., "metric alert"). - **query** (string) - Required - The monitor query. - **name** (string) - Required - The name of the monitor. - **message** (string) - Required - The alert message. - **tags** (array of strings) - Optional - Tags to associate with the monitor. - **options** (object) - Optional - Monitor configuration options. - **thresholds** (object) - Required if type is "metric alert". - **critical** (number) - The critical threshold. - **warning** (number) - The warning threshold. - **notify_no_data** (boolean) - Optional - Whether to notify if no data is received. - **no_data_timeframe** (integer) - Optional - Timeframe for no data notifications. - **renotify_interval** (integer) - Optional - Interval for renotification. - **escalation_message** (string) - Optional - Message for escalated alerts. - **include_tags** (boolean) - Optional - Whether to include tags in notifications. ### Request Example ```json { "type": "metric alert", "query": "avg(last_5m):avg:system.cpu.user{*} > 90", "name": "High CPU Usage Alert", "message": "CPU usage is above 90%!\n\nHost: {{host.name}}\nValue: {{value}}\n\n@slack-alerts @pagerduty", "tags": ["team:infrastructure", "severity:high"], "options": { "thresholds": { "critical": 90, "warning": 80 }, "notify_no_data": true, "no_data_timeframe": 10, "renotify_interval": 60, "escalation_message": "CPU still high after 1 hour! @oncall-team", "include_tags": true } } ``` ### Response #### Success Response (200) - **id** (integer) - The ID of the created monitor. ### Response Example ```json { "id": 12345 } ``` ## api.Monitor.get ### Description Retrieves monitor details. ### Method GET ### Endpoint /api/v1/monitor/{monitor_id} ### Parameters #### Path Parameters - **monitor_id** (integer) - Required - The ID of the monitor. #### Query Parameters - **group_states** (array of strings) - Optional - Filter by monitor states (e.g., ["alert", "warn"]). ### Response #### Success Response (200) - **overall_state** (string) - The overall state of the monitor. ### Response Example ```json { "overall_state": "alert" } ``` ## api.Monitor.update ### Description Updates an existing monitor. ### Method PUT ### Endpoint /api/v1/monitor/{monitor_id} ### Parameters #### Path Parameters - **monitor_id** (integer) - Required - The ID of the monitor to update. #### Request Body - **query** (string) - Optional - The updated monitor query. - **options** (object) - Optional - Updated monitor configuration options. - **thresholds** (object) - Optional. - **critical** (number) - The critical threshold. - **warning** (number) - The warning threshold. ### Response #### Success Response (200) - **id** (integer) - The ID of the updated monitor. ### Response Example ```json { "id": 12345 } ``` ## api.Monitor.mute ### Description Mutes a monitor. ### Method POST ### Endpoint /api/v1/monitor/{monitor_id}/mute ### Parameters #### Path Parameters - **monitor_id** (integer) - Required - The ID of the monitor to mute. #### Request Body - **scope** (string) - Required - The scope to mute the monitor for (e.g., "host:web-server-01"). - **end** (integer) - Required - The epoch timestamp when the mute should end. ### Response #### Success Response (200) - **message** (string) - Confirmation message. ### Response Example ```json { "message": "Monitor muted successfully." } ``` ## api.Monitor.unmute ### Description Unmutes a monitor. ### Method POST ### Endpoint /api/v1/monitor/{monitor_id}/unmute ### Parameters #### Path Parameters - **monitor_id** (integer) - Required - The ID of the monitor to unmute. #### Request Body - **scope** (string) - Required - The scope to unmute the monitor for (e.g., "host:web-server-01"). ### Response #### Success Response (200) - **message** (string) - Confirmation message. ### Response Example ```json { "message": "Monitor unmuted successfully." } ``` ## api.Monitor.get_all ### Description Lists all monitors with optional filters. ### Method GET ### Endpoint /api/v1/monitor ### Parameters #### Query Parameters - **tags** (array of strings) - Optional - Filter monitors by tags. - **monitor_tags** (array of strings) - Optional - Filter monitors by monitor-specific tags. ### Response #### Success Response (200) - **monitors** (array) - A list of monitor objects. - **name** (string) - The name of the monitor. - **overall_state** (string) - The overall state of the monitor. ### Response Example ```json [ { "name": "High CPU Usage Alert", "overall_state": "alert" } ] ``` ## api.Monitor.validate ### Description Validates a monitor definition before creation. ### Method POST ### Endpoint /api/v1/monitor/validate ### Parameters #### Request Body - **type** (string) - Required - The type of monitor. - **query** (string) - Required - The monitor query. ### Response #### Success Response (200) - **result** (string) - Validation result (e.g., "valid"). ### Response Example ```json { "result": "valid" } ``` ## api.Monitor.delete ### Description Deletes a monitor. ### Method DELETE ### Endpoint /api/v1/monitor/{monitor_id} ### Parameters #### Path Parameters - **monitor_id** (integer) - Required - The ID of the monitor to delete. ### Response #### Success Response (200) - **message** (string) - Confirmation message. ### Response Example ```json { "message": "Monitor deleted successfully." } ``` ``` -------------------------------- ### Create Datadog Event Source: https://github.com/datadog/datadogpy/blob/master/doc/source/index.md Use the datadog.api client to create an event with a title, text, and tags. ```default from datadog import api api.Event.create( title="Something big happened!", text="And let me tell you all about it here!", tags=["version:1", "application:web"], ) ``` -------------------------------- ### List Active Metrics Source: https://context7.com/datadog/datadogpy/llms.txt Retrieves a list of active metrics from the last 24 hours. Displays the first 10 metrics found. ```python active_metrics = api.Metric.list(from_epoch=now - 86400) # Last 24 hours print(f"Active metrics: {active_metrics['metrics'][:10]}") ``` -------------------------------- ### Create and Query Datadog Events Source: https://context7.com/datadog/datadogpy/llms.txt Post events to your Datadog Event Stream to track deployments, alerts, or significant occurrences. Supports creating simple or alert events with various options and querying events within a time range. ```python from datadog import initialize, api import time initialize(api_key="your_api_key", app_key="your_app_key") # Create a simple event response = api.Event.create( title="Deployment Started", text="Deploying version 2.1.0 to production servers", tags=["environment:production", "version:2.1.0"], ) print(f"Event created with ID: {response['event']['id']}") # Create an alert event with all options response = api.Event.create( title="High CPU Usage Detected", text="CPU usage exceeded 90% on web-server-01\n\nDetails:\n- Current: 94%\n- Threshold: 90%", alert_type="warning", # "error", "warning", "info", or "success" priority="normal", # "normal" or "low" tags=["host:web-server-01", "alert:cpu"], aggregation_key="cpu_alert_web01", source_type_name="my_apps", date_happened=int(time.time()), host="web-server-01", ) # Query events within a time range end_time = int(time.time()) start_time = end_time - 3600 # Last hour events = api.Event.query( start=start_time, end=end_time, priority="normal", tags=["environment:production"] ) for event in events.get("events", []): print(f"Event: {event['title']} at {event['date_happened']}") ``` -------------------------------- ### Add Tags to a Host Source: https://context7.com/datadog/datadogpy/llms.txt Add tags to a specific host. Tags are used for organizing and filtering infrastructure. An optional source can be specified. ```python # Add tags to a host api.Tag.create( host="web-server-01", tags=["env:production", "team:platform", "role:web"], source="users" # Optional: tag source ) ``` -------------------------------- ### Submit a Warning Service Check Source: https://context7.com/datadog/datadogpy/llms.txt Submit a service check with a WARNING status to indicate a potential issue that requires attention but is not yet critical. ```python # Submit a warning check api.ServiceCheck.check( check="myapp.disk_space", host_name="db-server-01", status=1, # WARNING message="Disk usage at 85%", tags=["component:database"] ) ```