Create or update usage quotas

Note: This endpoint is in Preview and is subject to change. If you have any feedback, contact Datadog support.

POST https://api.ap1.datadoghq.com/api/v2/usage/quotas/{quota_namespace}https://api.ap2.datadoghq.com/api/v2/usage/quotas/{quota_namespace}https://api.datadoghq.eu/api/v2/usage/quotas/{quota_namespace}https://api.ddog-gov.com/api/v2/usage/quotas/{quota_namespace}https://api.us2.ddog-gov.com/api/v2/usage/quotas/{quota_namespace}https://api.uk1.datadoghq.com/api/v2/usage/quotas/{quota_namespace}https://api.datadoghq.com/api/v2/usage/quotas/{quota_namespace}https://api.us3.datadoghq.com/api/v2/usage/quotas/{quota_namespace}https://api.us5.datadoghq.com/api/v2/usage/quotas/{quota_namespace}

Overview

Creates or updates one or more usage quotas by scope. If a quota already exists for a supplied scope, it is updated; otherwise, a new quota is created. Requires the billing_edit permission. This endpoint requires the billing_edit permission.

OAuth apps require the billing_edit authorization scope to access this endpoint.

Arguments

Path Parameters

Name

Type

Description

quota_namespace [required]

string

The product-specific namespace whose usage quotas are being managed.

Query Strings

Name

Type

Description

include_descendants

boolean

Whether to write every item in the request to the caller’s organization and all of its descendant organizations, instead of only the caller’s organization. Only descendants in the same datacenter are supported. For a user-handle scope, the quota is applied only to the caller’s organization and to descendant organizations where that user handle exists; the item fails only if the handle exists in none of them.

Request

Body Data (required)

The usage quotas to create or update.

Expand All

Field

Type

Description

data [required]

[object]

A bulk list of usage quota resources to create or update by scope.

attributes [required]

object

Attributes for creating or updating a usage quota by scope.

enforced [required]

boolean

Whether to actively block usage above the limit instead of only tracking or alerting on it.

scope

object

A namespace-specific key and value identifying what the quota applies to within an organization. The object must contain exactly one entry. Use "*" as the value for the default quota applied to entities without a specific quota, or omit the scope for an organization-wide quota. A specific value must identify an existing user handle in the caller's organization when include_descendants is false. When include_descendants is true, the handle must exist in the caller's organization or in at least one targeted descendant organization; the quota is then applied only to the organizations where that handle exists, and the request fails only if the handle exists in none of them.

<any-key>

string

usage_limit [required]

int64

The quota limit to set in the usage units defined by the quota namespace. For an organization-wide quota (scope omitted), the limit must be greater than the usage already recorded in the current period.

type [required]

enum

The JSON:API resource type for a usage quota. Allowed enum values: quotas

{
  "data": [
    {
      "attributes": {
        "enforced": true,
        "scope": {
          "<any-key>": "jane@example.com"
        },
        "usage_limit": 100000
      },
      "type": "quotas"
    }
  ]
}

Response

OK. The response includes each item's result; see each item's `error` attribute for any that failed to write.

Response containing the result of a bulk usage quota create-or-update request. Returned with a 200 status regardless of whether individual items succeeded or failed; check each item’s error attribute to determine its outcome.

Expand All

Field

Type

Description

data [required]

[object]

The results of writing each usage quota in a bulk create-or-update request, in the same order as the request.

attributes [required]

object

Attributes of a usage quota bulk write result. On success, all fields except error are present. On failure, only error is present and the other fields are omitted.

enforced

boolean

Whether usage above the limit is actively blocked instead of only tracked or alerted on. Omitted if this item failed to write.

error

string

An error message describing why this item failed to write. Omitted if this item was written successfully.

org_public_id

string

The public ID of the organization that owns the quota. Omitted if this item failed to write.

scope

object

A namespace-specific key and value identifying what the quota applies to within an organization. The object contains exactly one entry. A value of "*" identifies the default quota applied to entities without a specific quota. This field is omitted for an organization-wide quota.

<any-key>

string

usage_limit

double

The quota limit in the usage units defined by the quota namespace. May be fractional for quotas configured before public writes required whole units. Omitted if this item failed to write.

id [required]

string

An opaque usage quota identifier. Clients must pass this value back verbatim in update and delete requests and must not infer any structure from it.

type [required]

enum

The JSON:API resource type for a usage quota. Allowed enum values: quotas

{
  "data": [
    {
      "attributes": {
        "enforced": true,
        "error": "usage_limit is out of range",
        "org_public_id": "abcdef12345",
        "scope": {
          "<any-key>": "jane@example.com"
        },
        "usage_limit": 100000
      },
      "id": "MjAfYWlfY3JlZGl0c1911c2VyX2hhbmRsZTpfX0FMTF9f",
      "type": "quotas"
    }
  ]
}

Bad Request

API error response.

Expand All

Field

Type

Description

errors [required]

[object]

A list of errors.

detail

string

A human-readable explanation specific to this occurrence of the error.

meta

object

Non-standard meta-information about the error

source

object

References to the source of the error.

header

string

A string indicating the name of a single request header which caused the error.

parameter

string

A string indicating which URI query parameter caused the error.

pointer

string

A JSON pointer to the value in the request document that caused the error.

status

string

Status code of the response.

title

string

Short human-readable summary of the error.

{
  "errors": [
    {
      "detail": "Missing required attribute in body",
      "meta": {},
      "source": {
        "header": "Authorization",
        "parameter": "limit",
        "pointer": "/data/attributes/title"
      },
      "status": "400",
      "title": "Bad Request"
    }
  ]
}

Forbidden

API error response.

Expand All

Field

Type

Description

errors [required]

[object]

A list of errors.

detail

string

A human-readable explanation specific to this occurrence of the error.

meta

object

Non-standard meta-information about the error

source

object

References to the source of the error.

header

string

A string indicating the name of a single request header which caused the error.

parameter

string

A string indicating which URI query parameter caused the error.

pointer

string

A JSON pointer to the value in the request document that caused the error.

status

string

Status code of the response.

title

string

Short human-readable summary of the error.

{
  "errors": [
    {
      "detail": "Missing required attribute in body",
      "meta": {},
      "source": {
        "header": "Authorization",
        "parameter": "limit",
        "pointer": "/data/attributes/title"
      },
      "status": "400",
      "title": "Bad Request"
    }
  ]
}

Too many requests

API error response.

Expand All

Field

Type

Description

errors [required]

[string]

A list of errors.

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

Internal Server Error. Every item in the batch failed to write.

API error response.

Expand All

Field

Type

Description

errors [required]

[object]

A list of errors.

detail

string

A human-readable explanation specific to this occurrence of the error.

meta

object

Non-standard meta-information about the error

source

object

References to the source of the error.

header

string

A string indicating the name of a single request header which caused the error.

parameter

string

A string indicating which URI query parameter caused the error.

pointer

string

A JSON pointer to the value in the request document that caused the error.

status

string

Status code of the response.

title

string

Short human-readable summary of the error.

{
  "errors": [
    {
      "detail": "Missing required attribute in body",
      "meta": {},
      "source": {
        "header": "Authorization",
        "parameter": "limit",
        "pointer": "/data/attributes/title"
      },
      "status": "400",
      "title": "Bad Request"
    }
  ]
}

Code Example

                  ## Create or update quotas for the caller's organization.
# 

# Path parameters
export quota_namespace="ai_credits"
# Curl command
curl -X POST "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.uk1.datadoghq.com"https://api.datadoghq.com"https://api.us3.datadoghq.com"https://api.us5.datadoghq.com/api/v2/usage/quotas/${quota_namespace}" \ -H "Accept: application/json" \ -H "Content-Type: application/json" \ -H "DD-API-KEY: ${DD_API_KEY}" \ -H "DD-APPLICATION-KEY: ${DD_APP_KEY}" \ -d @- << EOF { "data": [ { "attributes": { "enforced": true, "scope": { "user_handle": "jane@example.com" }, "usage_limit": 100000 }, "type": "quotas" }, { "attributes": { "enforced": false, "scope": { "user_handle": "*" }, "usage_limit": 250000 }, "type": "quotas" } ] } EOF
"""
Create or update usage quotas returns "OK. The response includes each item's result; see each item's `error` attribute
for any that failed to write." response
"""

from datadog_api_client import ApiClient, Configuration
from datadog_api_client.v2.api.usage_metering_api import UsageMeteringApi
from datadog_api_client.v2.model.usage_quota_create_attributes import UsageQuotaCreateAttributes
from datadog_api_client.v2.model.usage_quota_create_data import UsageQuotaCreateData
from datadog_api_client.v2.model.usage_quota_request_scope import UsageQuotaRequestScope
from datadog_api_client.v2.model.usage_quota_type import UsageQuotaType
from datadog_api_client.v2.model.usage_quotas_create_request import UsageQuotasCreateRequest

body = UsageQuotasCreateRequest(
    data=[
        UsageQuotaCreateData(
            attributes=UsageQuotaCreateAttributes(
                enforced=True,
                scope=UsageQuotaRequestScope(
                    user_handle="jane@example.com",
                ),
                usage_limit=100000,
            ),
            type=UsageQuotaType.QUOTAS,
        ),
    ],
)

configuration = Configuration()
configuration.unstable_operations["create_quotas"] = True
with ApiClient(configuration) as api_client:
    api_instance = UsageMeteringApi(api_client)
    response = api_instance.create_quotas(quota_namespace="ai_credits", body=body)

    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.comuk1.datadoghq.comddog-gov.comus2.ddog-gov.com" DD_API_KEY="<DD_API_KEY>" DD_APP_KEY="<DD_APP_KEY>" python3 "example.py"
# Create or update usage quotas returns "OK. The response includes each item's result; see each item's `error` attribute
# for any that failed to write." response

require "datadog_api_client"
DatadogAPIClient.configure do |config|
  config.unstable_operations["v2.create_quotas".to_sym] = true
end
api_instance = DatadogAPIClient::V2::UsageMeteringAPI.new

body = DatadogAPIClient::V2::UsageQuotasCreateRequest.new({
  data: [
    DatadogAPIClient::V2::UsageQuotaCreateData.new({
      attributes: DatadogAPIClient::V2::UsageQuotaCreateAttributes.new({
        enforced: true,
        scope: {
          user_handle: "jane@example.com",
        },
        usage_limit: 100000,
      }),
      type: DatadogAPIClient::V2::UsageQuotaType::QUOTAS,
    }),
  ],
})
p api_instance.create_quotas("ai_credits", body)

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.comuk1.datadoghq.comddog-gov.comus2.ddog-gov.com" DD_API_KEY="<DD_API_KEY>" DD_APP_KEY="<DD_APP_KEY>" rb "example.rb"
// Create or update usage quotas returns "OK. The response includes each item's result; see each item's `error` attribute
// for any that failed to write." response

package main

import (
	"context"
	"encoding/json"
	"fmt"
	"os"

	"github.com/DataDog/datadog-api-client-go/v2/api/datadog"
	"github.com/DataDog/datadog-api-client-go/v2/api/datadogV2"
)

func main() {
	body := datadogV2.UsageQuotasCreateRequest{
		Data: []datadogV2.UsageQuotaCreateData{
			{
				Attributes: datadogV2.UsageQuotaCreateAttributes{
					Enforced: true,
					Scope: map[string]string{
						"user_handle": "jane@example.com",
					},
					UsageLimit: 100000,
				},
				Type: datadogV2.USAGEQUOTATYPE_QUOTAS,
			},
		},
	}
	ctx := datadog.NewDefaultContext(context.Background())
	configuration := datadog.NewConfiguration()
	configuration.SetUnstableOperationEnabled("v2.CreateQuotas", true)
	apiClient := datadog.NewAPIClient(configuration)
	api := datadogV2.NewUsageMeteringApi(apiClient)
	resp, r, err := api.CreateQuotas(ctx, "ai_credits", body, *datadogV2.NewCreateQuotasOptionalParameters())

	if err != nil {
		fmt.Fprintf(os.Stderr, "Error when calling `UsageMeteringApi.CreateQuotas`: %v\n", err)
		fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r)
	}

	responseContent, _ := json.MarshalIndent(resp, "", "  ")
	fmt.Fprintf(os.Stdout, "Response from `UsageMeteringApi.CreateQuotas`:\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.comuk1.datadoghq.comddog-gov.comus2.ddog-gov.com" DD_API_KEY="<DD_API_KEY>" DD_APP_KEY="<DD_APP_KEY>" go run "main.go"
// Create or update usage quotas returns "OK. The response includes each item's result; see each
// item's `error` attribute
// for any that failed to write." 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.model.UsageQuotaCreateAttributes;
import com.datadog.api.client.v2.model.UsageQuotaCreateData;
import com.datadog.api.client.v2.model.UsageQuotaType;
import com.datadog.api.client.v2.model.UsageQuotasBulkResponse;
import com.datadog.api.client.v2.model.UsageQuotasCreateRequest;
import java.util.Collections;
import java.util.Map;

public class Example {
  public static void main(String[] args) {
    ApiClient defaultClient = ApiClient.getDefaultApiClient();
    defaultClient.setUnstableOperationEnabled("v2.createQuotas", true);
    UsageMeteringApi apiInstance = new UsageMeteringApi(defaultClient);

    UsageQuotasCreateRequest body =
        new UsageQuotasCreateRequest()
            .data(
                Collections.singletonList(
                    new UsageQuotaCreateData()
                        .attributes(
                            new UsageQuotaCreateAttributes()
                                .enforced(true)
                                .scope(Map.ofEntries(Map.entry("user_handle", "jane@example.com")))
                                .usageLimit(100000L))
                        .type(UsageQuotaType.QUOTAS)));

    try {
      UsageQuotasBulkResponse result = apiInstance.createQuotas("ai_credits", body);
      System.out.println(result);
    } catch (ApiException e) {
      System.err.println("Exception when calling UsageMeteringApi#createQuotas");
      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.comuk1.datadoghq.comddog-gov.comus2.ddog-gov.com" DD_API_KEY="<DD_API_KEY>" DD_APP_KEY="<DD_APP_KEY>" java "Example.java"
// Create or update usage quotas returns "OK. The response includes each item's
// result; see each item's `error` attribute for any that failed to write."
// response
use datadog_api_client::datadog;
use datadog_api_client::datadogV2::api_usage_metering::CreateQuotasOptionalParams;
use datadog_api_client::datadogV2::api_usage_metering::UsageMeteringAPI;
use datadog_api_client::datadogV2::model::UsageQuotaCreateAttributes;
use datadog_api_client::datadogV2::model::UsageQuotaCreateData;
use datadog_api_client::datadogV2::model::UsageQuotaType;
use datadog_api_client::datadogV2::model::UsageQuotasCreateRequest;
use std::collections::BTreeMap;

#[tokio::main]
async fn main() {
    let body = UsageQuotasCreateRequest::new(vec![UsageQuotaCreateData::new(
        UsageQuotaCreateAttributes::new(true, 100000).scope(BTreeMap::from([(
            "user_handle".to_string(),
            "jane@example.com".to_string(),
        )])),
        UsageQuotaType::QUOTAS,
    )]);
    let mut configuration = datadog::Configuration::new();
    configuration.set_unstable_operation_enabled("v2.CreateQuotas", true);
    let api = UsageMeteringAPI::with_config(configuration);
    let resp = api
        .create_quotas(
            "ai_credits".to_string(),
            body,
            CreateQuotasOptionalParams::default(),
        )
        .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.comuk1.datadoghq.comddog-gov.comus2.ddog-gov.com" DD_API_KEY="<DD_API_KEY>" DD_APP_KEY="<DD_APP_KEY>" cargo run
/**
 * Create or update usage quotas returns "OK. The response includes each item's result; see each item's `error` attribute
 * for any that failed to write." response
 */

import { client, v2 } from "@datadog/datadog-api-client";

const configuration = client.createConfiguration();
configuration.unstableOperations["v2.createQuotas"] = true;
const apiInstance = new v2.UsageMeteringApi(configuration);

const params: v2.UsageMeteringApiCreateQuotasRequest = {
  body: {
    data: [
      {
        attributes: {
          enforced: true,
          scope: {
            user_handle: "jane@example.com",
          },
          usageLimit: 100000,
        },
        type: "quotas",
      },
    ],
  },
  quotaNamespace: "ai_credits",
};

apiInstance
  .createQuotas(params)
  .then((data: v2.UsageQuotasBulkResponse) => {
    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.comuk1.datadoghq.comddog-gov.comus2.ddog-gov.com" DD_API_KEY="<DD_API_KEY>" DD_APP_KEY="<DD_APP_KEY>" tsc "example.ts"