---
title: Crear una métrica basada en tramos
description: Crea una métrica basada en tramos ingerida en tu organización.
breadcrumbs: Documentación > API > Crear una métrica basada en tramos
---

> For the complete documentation index, see [llms.txt](https://dnd37xeb23o8n.cloudfront.net/stefon.simmons/docs-astro-web-10435/llms.txt).

# Crear una métrica basada en tramos

## v2 (latest)

| Datadog site      | API endpoint                                                 |
| ----------------- | ------------------------------------------------------------ |
| app.datadoghq.com | POST https://api.datadoghq.com/api/v2/apm/config/metrics     |
| us3.datadoghq.com | POST https://api.us3.datadoghq.com/api/v2/apm/config/metrics |
| us5.datadoghq.com | POST https://api.us5.datadoghq.com/api/v2/apm/config/metrics |
| app.datadoghq.eu  | POST https://api.datadoghq.eu/api/v2/apm/config/metrics      |
| ap1.datadoghq.com | POST https://api.ap1.datadoghq.com/api/v2/apm/config/metrics |
| ap2.datadoghq.com | POST https://api.ap2.datadoghq.com/api/v2/apm/config/metrics |
| uk1.datadoghq.com | POST https://api.uk1.datadoghq.com/api/v2/apm/config/metrics |
| app.ddog-gov.com  | POST https://api.ddog-gov.com/api/v2/apm/config/metrics      |
| us2.ddog-gov.com  | POST https://api.us2.ddog-gov.com/api/v2/apm/config/metrics  |

### Overview

Crea una métrica basada en tramos ingerida en tu organización.
Devuelve el objeto de métrica basada en tramos del cuerpo de la solicitud cuando la solicitud es correcta.

This endpoint requires the `apm_generate_metrics` permission.

### Request

#### Body Data (required)

La definición de la nueva métrica basada en tramos.

{% tabs %}
{% tab label="Model" %}
| Parent field | Field                         | Type     | Description                                                                                                                                |
| ------------ | ----------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
|              | data [*required*]             | object   | El nuevo cuerpo de la métrica basada en tramos.                                                                                            |
| data         | attributes [*required*]       | object   | The object describing the Datadog span-based metric to create.                                                                             |
| attributes   | compute [*required*]          | object   | The compute rule to compute the span-based metric.                                                                                         |
| compute      | aggregation_type [*required*] | enum     | The type of aggregation to use. Allowed enum values: `count`, `distribution`.                                                              |
| compute      | include_percentiles           | boolean  | Toggle to include or exclude percentile aggregations for distribution metrics. Only present when the `aggregation_type` is `distribution`. |
| compute      | path                          | string   | The path to the value the span-based metric will aggregate on (only used if the aggregation type is a "distribution").                     |
| attributes   | filter                        | object   | The span-based metric filter. Spans matching this filter will be aggregated in this metric.                                                |
| filter       | query                         | string   | The search query - following the span search syntax. Default: `*`.                                                                         |
| attributes   | group_by                      | [object] | The rules for the group by.                                                                                                                |
| group_by     | path [*required*]             | string   | The path to the value the span-based metric will be aggregated over.                                                                       |
| group_by     | tag_name                      | string   | Eventual name of the tag that gets created. By default, the path attribute is used as the tag name.                                        |
| data         | id [*required*]               | string   | The name of the span-based metric.                                                                                                         |
| data         | type [*required*]             | enum     | The type of resource. The value should always be spans_metrics. Allowed enum values: `spans_metrics`. Default: `spans_metrics`.            |
{% /tab %}

{% tab label="Example" %}
```json
{
  "data": {
    "attributes": {
      "compute": {
        "aggregation_type": "distribution",
        "include_percentiles": false,
        "path": "@duration"
      },
      "filter": {
        "query": "@http.status_code:200 service:my-service"
      },
      "group_by": [
        {
          "path": "resource_name",
          "tag_name": "resource_name"
        }
      ]
    },
    "id": "ExampleSpansMetric",
    "type": "spans_metrics"
  }
}
```
{% /tab %}
{% /tabs %}

### Response

{% tabs %}
{% tab label="200" %}
OK

{% tabs %}
{% tab label="Model" %}
The span-based metric object.

| Parent field | Field               | Type     | Description                                                                                                                                |
| ------------ | ------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
|              | data                | object   | The span-based metric properties.                                                                                                          |
| data         | attributes          | object   | The object describing a Datadog span-based metric.                                                                                         |
| attributes   | compute             | object   | The compute rule to compute the span-based metric.                                                                                         |
| compute      | aggregation_type    | enum     | The type of aggregation to use. Allowed enum values: `count`, `distribution`.                                                              |
| compute      | include_percentiles | boolean  | Toggle to include or exclude percentile aggregations for distribution metrics. Only present when the `aggregation_type` is `distribution`. |
| compute      | path                | string   | The path to the value the span-based metric will aggregate on (only used if the aggregation type is a "distribution").                     |
| attributes   | filter              | object   | The span-based metric filter. Spans matching this filter will be aggregated in this metric.                                                |
| filter       | query               | string   | The search query - following the span search syntax.                                                                                       |
| attributes   | group_by            | [object] | The rules for the group by.                                                                                                                |
| group_by     | path                | string   | The path to the value the span-based metric will be aggregated over.                                                                       |
| group_by     | tag_name            | string   | Eventual name of the tag that gets created. By default, the path attribute is used as the tag name.                                        |
| data         | id                  | string   | The name of the span-based metric.                                                                                                         |
| data         | type                | enum     | The type of resource. The value should always be spans_metrics. Allowed enum values: `spans_metrics`. Default: `spans_metrics`.            |
{% /tab %}

{% tab label="Example" %}
```json
{
  "data": {
    "attributes": {
      "compute": {
        "aggregation_type": "distribution",
        "include_percentiles": false,
        "path": "@duration"
      },
      "filter": {
        "query": "@http.status_code:200 service:my-service"
      },
      "group_by": [
        {
          "path": "resource_name",
          "tag_name": "resource_name"
        }
      ]
    },
    "id": "my.metric",
    "type": "spans_metrics"
  }
}
```
{% /tab %}
{% /tabs %}
{% /tab %}

{% tab label="400" %}
Bad Request

{% tabs %}
{% tab label="Model" %}
API error response.

| Field               | Type     | Description       |
| ------------------- | -------- | ----------------- |
| errors [*required*] | [string] | A list of errors. |
{% /tab %}

{% tab label="Example" %}
```json
{
  "errors": [
    "Bad Request"
  ]
}
```
{% /tab %}
{% /tabs %}
{% /tab %}

{% tab label="403" %}
Not Authorized

{% tabs %}
{% tab label="Model" %}
API error response.

| Field               | Type     | Description       |
| ------------------- | -------- | ----------------- |
| errors [*required*] | [string] | A list of errors. |
{% /tab %}

{% tab label="Example" %}
```json
{
  "errors": [
    "Bad Request"
  ]
}
```
{% /tab %}
{% /tabs %}
{% /tab %}

{% tab label="409" %}
Conflict

{% tabs %}
{% tab label="Model" %}
API error response.

| Field               | Type     | Description       |
| ------------------- | -------- | ----------------- |
| errors [*required*] | [string] | A list of errors. |
{% /tab %}

{% tab label="Example" %}
```json
{
  "errors": [
    "Bad Request"
  ]
}
```
{% /tab %}
{% /tabs %}
{% /tab %}

{% tab label="429" %}
Too many requests

{% tabs %}
{% tab label="Model" %}
API error response.

| Field               | Type     | Description       |
| ------------------- | -------- | ----------------- |
| errors [*required*] | [string] | A list of errors. |
{% /tab %}

{% tab label="Example" %}
```json
{
  "errors": [
    "Bad Request"
  ]
}
```
{% /tab %}
{% /tabs %}
{% /tab %}
{% /tabs %}

### Code Example

{% tabs %}
{% tab label="Curl" %}
```bash
# Set your Datadog site and credentials
export DD_SITE="datadoghq.com" # Or us3.datadoghq.com, us5.datadoghq.com, datadoghq.eu, ap1.datadoghq.com, ap2.datadoghq.com, uk1.datadoghq.com, ddog-gov.com, us2.ddog-gov.com
# Use a Personal Access Token or Service Access Token
export DD_BEARER_TOKEN="<PERSONAL_ACCESS_TOKEN OR SERVICE_ACCESS_TOKEN>"

curl -X POST "https://api.${DD_SITE}/api/v2/apm/config/metrics" \
-H "Accept: application/json" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer ${DD_BEARER_TOKEN}" \
-d @- << EOF
{
  "data": {
    "attributes": {
      "compute": {
        "aggregation_type": "distribution",
        "include_percentiles": false,
        "path": "@duration"
      },
      "filter": {
        "query": "@http.status_code:200 service:my-service"
      },
      "group_by": [
        {
          "path": "resource_name",
          "tag_name": "resource_name"
        }
      ]
    },
    "id": "ExampleSpansMetric",
    "type": "spans_metrics"
  }
}
EOF
```
{% /tab %}

{% tab label="Go" %}
```go
// Create a span-based metric returns "OK" 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.SpansMetricCreateRequest{
		Data: datadogV2.SpansMetricCreateData{
			Attributes: datadogV2.SpansMetricCreateAttributes{
				Compute: datadogV2.SpansMetricCompute{
					AggregationType:    datadogV2.SPANSMETRICCOMPUTEAGGREGATIONTYPE_DISTRIBUTION,
					IncludePercentiles: datadog.PtrBool(false),
					Path:               datadog.PtrString("@duration"),
				},
				Filter: &datadogV2.SpansMetricFilter{
					Query: datadog.PtrString("@http.status_code:200 service:my-service"),
				},
				GroupBy: []datadogV2.SpansMetricGroupBy{
					{
						Path:    "resource_name",
						TagName: datadog.PtrString("resource_name"),
					},
				},
			},
			Id:   "ExampleSpansMetric",
			Type: datadogV2.SPANSMETRICTYPE_SPANS_METRICS,
		},
	}
	ctx := datadog.NewDefaultContext(context.Background())
	ctx = context.WithValue(ctx, datadog.ContextAccessToken, os.Getenv("DD_BEARER_TOKEN"))
	configuration := datadog.NewConfiguration()
	apiClient := datadog.NewAPIClient(configuration)
	api := datadogV2.NewSpansMetricsApi(apiClient)
	resp, r, err := api.CreateSpansMetric(ctx, body)

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

	responseContent, _ := json.MarshalIndent(resp, "", "  ")
	fmt.Fprintf(os.Stdout, "Response from `SpansMetricsApi.CreateSpansMetric`:\n%s\n", responseContent)
}
```

#### Instructions

First [install the library and its dependencies](https://dnd37xeb23o8n.cloudfront.net/api/latest.md?code-lang=go) and then save the example to `main.go` and run following commands:

```bash
DD_SITE="datadoghq.com" DD_BEARER_TOKEN="<PERSONAL_ACCESS_TOKEN OR SERVICE_ACCESS_TOKEN>" go run "main.go"
```
{% /tab %}

{% tab label="Java" %}
```java
// Create a span-based metric returns "OK" response

import com.datadog.api.client.ApiClient;
import com.datadog.api.client.ApiException;
import com.datadog.api.client.v2.api.SpansMetricsApi;
import com.datadog.api.client.v2.model.SpansMetricCompute;
import com.datadog.api.client.v2.model.SpansMetricComputeAggregationType;
import com.datadog.api.client.v2.model.SpansMetricCreateAttributes;
import com.datadog.api.client.v2.model.SpansMetricCreateData;
import com.datadog.api.client.v2.model.SpansMetricCreateRequest;
import com.datadog.api.client.v2.model.SpansMetricFilter;
import com.datadog.api.client.v2.model.SpansMetricGroupBy;
import com.datadog.api.client.v2.model.SpansMetricResponse;
import com.datadog.api.client.v2.model.SpansMetricType;
import java.util.Collections;

public class Example {
  public static void main(String[] args) {
    ApiClient defaultClient = ApiClient.getDefaultApiClient();
    defaultClient.setAccessToken(System.getenv("DD_BEARER_TOKEN"));
    SpansMetricsApi apiInstance = new SpansMetricsApi(defaultClient);

    SpansMetricCreateRequest body =
        new SpansMetricCreateRequest()
            .data(
                new SpansMetricCreateData()
                    .attributes(
                        new SpansMetricCreateAttributes()
                            .compute(
                                new SpansMetricCompute()
                                    .aggregationType(SpansMetricComputeAggregationType.DISTRIBUTION)
                                    .includePercentiles(false)
                                    .path("@duration"))
                            .filter(
                                new SpansMetricFilter()
                                    .query("@http.status_code:200 service:my-service"))
                            .groupBy(
                                Collections.singletonList(
                                    new SpansMetricGroupBy()
                                        .path("resource_name")
                                        .tagName("resource_name"))))
                    .id("ExampleSpansMetric")
                    .type(SpansMetricType.SPANS_METRICS));

    try {
      SpansMetricResponse result = apiInstance.createSpansMetric(body);
      System.out.println(result);
    } catch (ApiException e) {
      System.err.println("Exception when calling SpansMetricsApi#createSpansMetric");
      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](https://dnd37xeb23o8n.cloudfront.net/api/latest.md?code-lang=java) and then save the example to `Example.java` and run following commands:

```bash
DD_SITE="datadoghq.com" DD_BEARER_TOKEN="<PERSONAL_ACCESS_TOKEN OR SERVICE_ACCESS_TOKEN>" java "Example.java"
```
{% /tab %}

{% tab label="Python" %}
```python
"""
Create a span-based metric returns "OK" response
"""

from os import environ
from datadog_api_client import ApiClient, Configuration
from datadog_api_client.v2.api.spans_metrics_api import SpansMetricsApi
from datadog_api_client.v2.model.spans_metric_compute import SpansMetricCompute
from datadog_api_client.v2.model.spans_metric_compute_aggregation_type import SpansMetricComputeAggregationType
from datadog_api_client.v2.model.spans_metric_create_attributes import SpansMetricCreateAttributes
from datadog_api_client.v2.model.spans_metric_create_data import SpansMetricCreateData
from datadog_api_client.v2.model.spans_metric_create_request import SpansMetricCreateRequest
from datadog_api_client.v2.model.spans_metric_filter import SpansMetricFilter
from datadog_api_client.v2.model.spans_metric_group_by import SpansMetricGroupBy
from datadog_api_client.v2.model.spans_metric_type import SpansMetricType

body = SpansMetricCreateRequest(
    data=SpansMetricCreateData(
        attributes=SpansMetricCreateAttributes(
            compute=SpansMetricCompute(
                aggregation_type=SpansMetricComputeAggregationType.DISTRIBUTION,
                include_percentiles=False,
                path="@duration",
            ),
            filter=SpansMetricFilter(
                query="@http.status_code:200 service:my-service",
            ),
            group_by=[
                SpansMetricGroupBy(
                    path="resource_name",
                    tag_name="resource_name",
                ),
            ],
        ),
        id="ExampleSpansMetric",
        type=SpansMetricType.SPANS_METRICS,
    ),
)

configuration = Configuration()
configuration.access_token = environ["DD_BEARER_TOKEN"]
with ApiClient(configuration) as api_client:
    api_instance = SpansMetricsApi(api_client)
    response = api_instance.create_spans_metric(body=body)

    print(response)
```

#### Instructions

First [install the library and its dependencies](https://dnd37xeb23o8n.cloudfront.net/api/latest.md?code-lang=python) and then save the example to `example.py` and run following commands:

```bash
DD_SITE="datadoghq.com" DD_BEARER_TOKEN="<PERSONAL_ACCESS_TOKEN OR SERVICE_ACCESS_TOKEN>" python3 "example.py"
```
{% /tab %}

{% tab label="Ruby" %}
```ruby
# Create a span-based metric returns "OK" response

require "datadog_api_client"
DatadogAPIClient.configure do |config|
  config.access_token = ENV["DD_BEARER_TOKEN"]
end
api_instance = DatadogAPIClient::V2::SpansMetricsAPI.new

body = DatadogAPIClient::V2::SpansMetricCreateRequest.new({
  data: DatadogAPIClient::V2::SpansMetricCreateData.new({
    attributes: DatadogAPIClient::V2::SpansMetricCreateAttributes.new({
      compute: DatadogAPIClient::V2::SpansMetricCompute.new({
        aggregation_type: DatadogAPIClient::V2::SpansMetricComputeAggregationType::DISTRIBUTION,
        include_percentiles: false,
        path: "@duration",
      }),
      filter: DatadogAPIClient::V2::SpansMetricFilter.new({
        query: "@http.status_code:200 service:my-service",
      }),
      group_by: [
        DatadogAPIClient::V2::SpansMetricGroupBy.new({
          path: "resource_name",
          tag_name: "resource_name",
        }),
      ],
    }),
    id: "ExampleSpansMetric",
    type: DatadogAPIClient::V2::SpansMetricType::SPANS_METRICS,
  }),
})
p api_instance.create_spans_metric(body)
```

#### Instructions

First [install the library and its dependencies](https://dnd37xeb23o8n.cloudfront.net/api/latest.md?code-lang=ruby) and then save the example to `example.rb` and run following commands:

```bash
DD_SITE="datadoghq.com" DD_BEARER_TOKEN="<PERSONAL_ACCESS_TOKEN OR SERVICE_ACCESS_TOKEN>" rb "example.rb"
```
{% /tab %}

{% tab label="Rust" %}
```rust
// Create a span-based metric returns "OK" response
use datadog_api_client::datadog;
use datadog_api_client::datadogV2::api_spans_metrics::SpansMetricsAPI;
use datadog_api_client::datadogV2::model::SpansMetricCompute;
use datadog_api_client::datadogV2::model::SpansMetricComputeAggregationType;
use datadog_api_client::datadogV2::model::SpansMetricCreateAttributes;
use datadog_api_client::datadogV2::model::SpansMetricCreateData;
use datadog_api_client::datadogV2::model::SpansMetricCreateRequest;
use datadog_api_client::datadogV2::model::SpansMetricFilter;
use datadog_api_client::datadogV2::model::SpansMetricGroupBy;
use datadog_api_client::datadogV2::model::SpansMetricType;

#[tokio::main]
async fn main() {
    let body = SpansMetricCreateRequest::new(SpansMetricCreateData::new(
        SpansMetricCreateAttributes::new(
            SpansMetricCompute::new(SpansMetricComputeAggregationType::DISTRIBUTION)
                .include_percentiles(false)
                .path("@duration".to_string()),
        )
        .filter(
            SpansMetricFilter::new().query("@http.status_code:200 service:my-service".to_string()),
        )
        .group_by(vec![SpansMetricGroupBy::new("resource_name".to_string())
            .tag_name("resource_name".to_string())]),
        "ExampleSpansMetric".to_string(),
        SpansMetricType::SPANS_METRICS,
    ));
    let configuration = datadog::Configuration::new();
    let api = SpansMetricsAPI::with_config(configuration);
    let resp = api.create_spans_metric(body).await;
    if let Ok(value) = resp {
        println!("{:#?}", value);
    } else {
        println!("{:#?}", resp.unwrap_err());
    }
}
```

#### Instructions

First [install the library and its dependencies](https://dnd37xeb23o8n.cloudfront.net/api/latest.md?code-lang=rust) and then save the example to `src/main.rs` and run following commands:

```bash
DD_SITE="datadoghq.com" DD_API_KEY="<API-KEY>" DD_APP_KEY="<APP-KEY>" cargo run
```
{% /tab %}

{% tab label="TypeScript" %}
```typescript
/**
 * Create a span-based metric returns "OK" response
 */

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

const configuration = client.createConfiguration({
  authMethods: {
    AuthZ: {
      accessToken: process.env.DD_BEARER_TOKEN as string,
    },
  },
});
const apiInstance = new v2.SpansMetricsApi(configuration);

const params: v2.SpansMetricsApiCreateSpansMetricRequest = {
  body: {
    data: {
      attributes: {
        compute: {
          aggregationType: "distribution",
          includePercentiles: false,
          path: "@duration",
        },
        filter: {
          query: "@http.status_code:200 service:my-service",
        },
        groupBy: [
          {
            path: "resource_name",
            tagName: "resource_name",
          },
        ],
      },
      id: "ExampleSpansMetric",
      type: "spans_metrics",
    },
  },
};

apiInstance
  .createSpansMetric(params)
  .then((data: v2.SpansMetricResponse) => {
    console.log(
      "API called successfully. Returned data: " + JSON.stringify(data)
    );
  })
  .catch((error: any) => console.error(error));
```

#### Instructions

First [install the library and its dependencies](https://dnd37xeb23o8n.cloudfront.net/api/latest.md?code-lang=typescript) and then save the example to `example.ts` and run following commands:

```bash
DD_SITE="datadoghq.com" DD_BEARER_TOKEN="<PERSONAL_ACCESS_TOKEN OR SERVICE_ACCESS_TOKEN>" tsc "example.ts"
```
{% /tab %}
{% /tabs %}
