Get Monthly Cost Attribution

GET https://api.ap1.datadoghq.com/api/v2/cost_by_tag/monthly_cost_attributionhttps://api.ap2.datadoghq.com/api/v2/cost_by_tag/monthly_cost_attributionhttps://api.datadoghq.eu/api/v2/cost_by_tag/monthly_cost_attributionhttps://api.ddog-gov.com/api/v2/cost_by_tag/monthly_cost_attributionhttps://api.us2.ddog-gov.com/api/v2/cost_by_tag/monthly_cost_attributionhttps://api.datadoghq.com/api/v2/cost_by_tag/monthly_cost_attributionhttps://api.us3.datadoghq.com/api/v2/cost_by_tag/monthly_cost_attributionhttps://api.us5.datadoghq.com/api/v2/cost_by_tag/monthly_cost_attribution

Overview

Get monthly cost attribution by tag across multi-org and single root-org accounts. Cost Attribution data for a given month becomes available no later than the 19th of the following month. This API endpoint is paginated. To make sure you receive all records, check if the value of next_record_id is set in the response. If it is, make another request and pass next_record_id as a parameter. Pseudo code example:

response := GetMonthlyCostAttribution(start_month, end_month)
cursor := response.metadata.pagination.next_record_id
WHILE cursor != null BEGIN
  sleep(5 seconds)  # Avoid running into rate limit
  response := GetMonthlyCostAttribution(start_month, end_month, next_record_id=cursor)
  cursor := response.metadata.pagination.next_record_id
END

This endpoint is only accessible for parent-level organizations. This endpoint is not available in the Government (US1-FED) site.

This endpoint requires all of the following permissions:
  • usage_read
  • billing_read

  • OAuth apps require the usage_read, billing_read authorization scope to access this endpoint.

    Arguments

    Query Strings

    Name

    Type

    Description

    start_month [required]

    string

    Datetime in ISO-8601 format, UTC, precise to month: [YYYY-MM] for cost beginning in this month.

    end_month

    string

    Datetime in ISO-8601 format, UTC, precise to month: [YYYY-MM] for cost ending this month.

    fields [required]

    string

    Comma-separated list specifying cost types (e.g., <billing_dimension>_on_demand_cost, <billing_dimension>_committed_cost, <billing_dimension>_total_cost) and the proportions (<billing_dimension>_percentage_in_org, <billing_dimension>_percentage_in_account). Use * to retrieve all fields. Example: infra_host_on_demand_cost,infra_host_percentage_in_account To obtain the complete list of active billing dimensions that can be used to replace <billing_dimension> in the field names, make a request to the Get active billing dimensions API.

    sort_direction

    enum

    The direction to sort by: [desc, asc].
    Allowed enum values: desc, asc

    sort_name

    string

    The billing dimension to sort by. Always sorted by total cost. Example: infra_host.

    tag_breakdown_keys

    string

    Comma separated list of tag keys used to group cost. If no value is provided the cost will not be broken down by tags. To see which tags are available, look for the value of tag_config_source in the API response.

    next_record_id

    string

    List following results with a next_record_id provided in the previous query.

    include_descendants

    boolean

    Include child org cost in the response. Defaults to true.

    Response

    OK

    Response containing the monthly cost attribution by tag(s).

    Expand All

    Field

    Type

    Description

    data

    [object]

    Response containing cost attribution.

    attributes

    object

    Cost Attribution by Tag for a given organization.

    month

    date-time

    Datetime in ISO-8601 format, UTC, precise to hour: [YYYY-MM-DDThh].

    org_name

    string

    The name of the organization.

    public_id

    string

    The organization public ID.

    tag_config_source

    string

    The source of the cost attribution tag configuration and the selected tags in the format <source_org_name>:::<selected tag 1>///<selected tag 2>///<selected tag 3>.

    tags

    object

    Tag keys and values. A null value here means that the requested tag breakdown cannot be applied because it does not match the tags configured for usage attribution. In this scenario the API returns the total cost, not broken down by tags.

    <any-key>

    [string]

    A list of values that are associated with each tag key.

    • An empty list means the resource use wasn't tagged with the respective tag.
    • Multiple values means the respective tag was applied multiple times on the resource.
    • An <empty> value means the resource was tagged with the respective tag but did not have a value.

    updated_at

    string

    Shows the most recent hour in the current months for all organizations for which all costs were calculated.

    values

    object

    Fields in Cost Attribution by tag(s). Example: infra_host_on_demand_cost, infra_host_committed_cost, infra_host_total_cost, infra_host_percentage_in_org, infra_host_percentage_in_account.

    id

    string

    Unique ID of the response.

    type

    enum

    Type of cost attribution data. Allowed enum values: cost_by_tag

    default: cost_by_tag

    meta

    object

    The object containing document metadata.

    aggregates

    [object]

    An array of available aggregates.

    agg_type

    string

    The aggregate type.

    field

    string

    The field.

    value

    double

    The value for a given field.

    pagination

    object

    The metadata for the current pagination.

    next_record_id

    string

    The cursor to use to get the next results, if any. To make the next request, use the same parameters with the addition of the next_record_id.

    {
      "data": [
        {
          "attributes": {
            "month": "2019-09-19T10:00:00.000Z",
            "org_name": "string",
            "public_id": "string",
            "tag_config_source": "string",
            "tags": {
              "<any-key>": [
                "datadog-integrations-lab"
              ]
            },
            "updated_at": "string",
            "values": {}
          },
          "id": "string",
          "type": "cost_by_tag"
        }
      ],
      "meta": {
        "aggregates": [
          {
            "agg_type": "sum",
            "field": "infra_host_committed_cost",
            "value": "number"
          }
        ],
        "pagination": {
          "next_record_id": "string"
        }
      }
    }

    Bad Request

    API error response.

    Expand All

    Field

    Type

    Description

    errors [required]

    [string]

    A list of errors.

    {
      "errors": [
        "Bad Request"
      ]
    }

    Forbidden - User is not authorized

    API error response.

    Expand All

    Field

    Type

    Description

    errors [required]

    [string]

    A list of errors.

    {
      "errors": [
        "Bad Request"
      ]
    }

    Too many requests

    API error response.

    Expand All

    Field

    Type

    Description

    errors [required]

    [string]

    A list of errors.

    {
      "errors": [
        "Bad Request"
      ]
    }

    Code Example

                      # Required query arguments
    export start_month="CHANGE_ME"
    export fields="CHANGE_ME"
    # Curl command
    curl -X GET "https://api.ap1.datadoghq.com"https://api.ap2.datadoghq.com"https://api.datadoghq.eu"https://api.ddog-gov.com"https://api.us2.ddog-gov.com"https://api.datadoghq.com"https://api.us3.datadoghq.com"https://api.us5.datadoghq.com/api/v2/cost_by_tag/monthly_cost_attribution?start_month=${start_month}&fields=${fields}" \ -H "Accept: application/json" \ -H "DD-API-KEY: ${DD_API_KEY}" \ -H "DD-APPLICATION-KEY: ${DD_APP_KEY}"
    """
    Get Monthly Cost Attribution returns "OK" response
    """
    
    from datetime import datetime
    from dateutil.relativedelta import relativedelta
    from datadog_api_client import ApiClient, Configuration
    from datadog_api_client.v2.api.usage_metering_api import UsageMeteringApi
    
    configuration = Configuration()
    with ApiClient(configuration) as api_client:
        api_instance = UsageMeteringApi(api_client)
        response = api_instance.get_monthly_cost_attribution(
            start_month=(datetime.now() + relativedelta(days=-5)),
            end_month=(datetime.now() + relativedelta(days=-3)),
            fields="infra_host_total_cost",
        )
    
        print(response)
    

    Instructions

    First install the library and its dependencies and then save the example to example.py and run following commands:

        
    DD_SITE="datadoghq.comus3.datadoghq.comus5.datadoghq.comdatadoghq.euap1.datadoghq.comap2.datadoghq.comddog-gov.comus2.ddog-gov.com" DD_API_KEY="<DD_API_KEY>" DD_APP_KEY="<DD_APP_KEY>" python3 "example.py"
    # Get Monthly Cost Attribution returns "OK" response
    
    require "datadog_api_client"
    api_instance = DatadogAPIClient::V2::UsageMeteringAPI.new
    opts = {
      end_month: (Time.now + -3 * 86400),
    }
    p api_instance.get_monthly_cost_attribution((Time.now + -5 * 86400), "infra_host_total_cost", opts)
    

    Instructions

    First install the library and its dependencies and then save the example to example.rb and run following commands:

        
    DD_SITE="datadoghq.comus3.datadoghq.comus5.datadoghq.comdatadoghq.euap1.datadoghq.comap2.datadoghq.comddog-gov.comus2.ddog-gov.com" DD_API_KEY="<DD_API_KEY>" DD_APP_KEY="<DD_APP_KEY>" rb "example.rb"
    // Get Monthly Cost Attribution returns "OK" response
    
    package main
    
    import (
    	"context"
    	"encoding/json"
    	"fmt"
    	"os"
    	"time"
    
    	"github.com/DataDog/datadog-api-client-go/v2/api/datadog"
    	"github.com/DataDog/datadog-api-client-go/v2/api/datadogV2"
    )
    
    func main() {
    	ctx := datadog.NewDefaultContext(context.Background())
    	configuration := datadog.NewConfiguration()
    	apiClient := datadog.NewAPIClient(configuration)
    	api := datadogV2.NewUsageMeteringApi(apiClient)
    	resp, r, err := api.GetMonthlyCostAttribution(ctx, time.Now().AddDate(0, 0, -5), "infra_host_total_cost", *datadogV2.NewGetMonthlyCostAttributionOptionalParameters().WithEndMonth(time.Now().AddDate(0, 0, -3)))
    
    	if err != nil {
    		fmt.Fprintf(os.Stderr, "Error when calling `UsageMeteringApi.GetMonthlyCostAttribution`: %v\n", err)
    		fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r)
    	}
    
    	responseContent, _ := json.MarshalIndent(resp, "", "  ")
    	fmt.Fprintf(os.Stdout, "Response from `UsageMeteringApi.GetMonthlyCostAttribution`:\n%s\n", responseContent)
    }
    

    Instructions

    First install the library and its dependencies and then save the example to main.go and run following commands:

        
    DD_SITE="datadoghq.comus3.datadoghq.comus5.datadoghq.comdatadoghq.euap1.datadoghq.comap2.datadoghq.comddog-gov.comus2.ddog-gov.com" DD_API_KEY="<DD_API_KEY>" DD_APP_KEY="<DD_APP_KEY>" go run "main.go"
    // Get Monthly Cost Attribution returns "OK" response
    import com.datadog.api.client.ApiClient;
    import com.datadog.api.client.ApiException;
    import com.datadog.api.client.v2.api.UsageMeteringApi;
    import com.datadog.api.client.v2.api.UsageMeteringApi.GetMonthlyCostAttributionOptionalParameters;
    import com.datadog.api.client.v2.model.MonthlyCostAttributionResponse;
    import java.time.OffsetDateTime;
    
    public class Example {
      public static void main(String[] args) {
        ApiClient defaultClient = ApiClient.getDefaultApiClient();
        UsageMeteringApi apiInstance = new UsageMeteringApi(defaultClient);
    
        try {
          MonthlyCostAttributionResponse result =
              apiInstance.getMonthlyCostAttribution(
                  OffsetDateTime.now().plusDays(-5),
                  "infra_host_total_cost",
                  new GetMonthlyCostAttributionOptionalParameters()
                      .endMonth(OffsetDateTime.now().plusDays(-3)));
          System.out.println(result);
        } catch (ApiException e) {
          System.err.println("Exception when calling UsageMeteringApi#getMonthlyCostAttribution");
          System.err.println("Status code: " + e.getCode());
          System.err.println("Reason: " + e.getResponseBody());
          System.err.println("Response headers: " + e.getResponseHeaders());
          e.printStackTrace();
        }
      }
    }
    

    Instructions

    First install the library and its dependencies and then save the example to Example.java and run following commands:

        
    DD_SITE="datadoghq.comus3.datadoghq.comus5.datadoghq.comdatadoghq.euap1.datadoghq.comap2.datadoghq.comddog-gov.comus2.ddog-gov.com" DD_API_KEY="<DD_API_KEY>" DD_APP_KEY="<DD_APP_KEY>" java "Example.java"
    // Get Monthly Cost Attribution returns "OK" response
    use chrono::{DateTime, Utc};
    use datadog_api_client::datadog;
    use datadog_api_client::datadogV2::api_usage_metering::GetMonthlyCostAttributionOptionalParams;
    use datadog_api_client::datadogV2::api_usage_metering::UsageMeteringAPI;
    
    #[tokio::main]
    async fn main() {
        let configuration = datadog::Configuration::new();
        let api = UsageMeteringAPI::with_config(configuration);
        let resp = api
            .get_monthly_cost_attribution(
                DateTime::parse_from_rfc3339("2021-11-06T11:11:11+00:00")
                    .expect("Failed to parse datetime")
                    .with_timezone(&Utc),
                "infra_host_total_cost".to_string(),
                GetMonthlyCostAttributionOptionalParams::default().end_month(
                    DateTime::parse_from_rfc3339("2021-11-08T11:11:11+00:00")
                        .expect("Failed to parse datetime")
                        .with_timezone(&Utc),
                ),
            )
            .await;
        if let Ok(value) = resp {
            println!("{:#?}", value);
        } else {
            println!("{:#?}", resp.unwrap_err());
        }
    }
    

    Instructions

    First install the library and its dependencies and then save the example to src/main.rs and run following commands:

        
    DD_SITE="datadoghq.comus3.datadoghq.comus5.datadoghq.comdatadoghq.euap1.datadoghq.comap2.datadoghq.comddog-gov.comus2.ddog-gov.com" DD_API_KEY="<DD_API_KEY>" DD_APP_KEY="<DD_APP_KEY>" cargo run
    /**
     * Get Monthly Cost Attribution returns "OK" response
     */
    
    import { client, v2 } from "@datadog/datadog-api-client";
    
    const configuration = client.createConfiguration();
    const apiInstance = new v2.UsageMeteringApi(configuration);
    
    const params: v2.UsageMeteringApiGetMonthlyCostAttributionRequest = {
      startMonth: new Date(new Date().getTime() + -5 * 86400 * 1000),
      endMonth: new Date(new Date().getTime() + -3 * 86400 * 1000),
      fields: "infra_host_total_cost",
    };
    
    apiInstance
      .getMonthlyCostAttribution(params)
      .then((data: v2.MonthlyCostAttributionResponse) => {
        console.log(
          "API called successfully. Returned data: " + JSON.stringify(data)
        );
      })
      .catch((error: any) => console.error(error));
    

    Instructions

    First install the library and its dependencies and then save the example to example.ts and run following commands:

        
    DD_SITE="datadoghq.comus3.datadoghq.comus5.datadoghq.comdatadoghq.euap1.datadoghq.comap2.datadoghq.comddog-gov.comus2.ddog-gov.com" DD_API_KEY="<DD_API_KEY>" DD_APP_KEY="<DD_APP_KEY>" tsc "example.ts"