> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://respan.ai/docs/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://respan.ai/docs/_mcp/server.

# List span groups with filters

POST https://api.respan.ai/api/request-logs/groups/
Content-Type: application/json

Group spans using the same query parameters as GET and optional standard Respan filters in the request body.

Reference: https://respan.ai/docs/apis/spans/list-span-groups-with-filters

## Authentication

- `Authorization` header (bearer token, required) — Use your Respan API key for Respan API authentication. Enter only the Respan API key value; clients send Authorization: Bearer \<RESPAN\_API\_KEY>. For /api/responses, provider credentials such as Perplexity, OpenAI, or Azure OpenAI go in Settings -> Providers or respan\_params.credential\_override in the request body, not in this authentication field.
- `Authorization` header (bearer token, required) — Use a dashboard JWT only for dashboard-authenticated endpoints. Respan API-key endpoints use the respanApiKey auth field instead.

## Request

### Query parameters

- `group_by` (enum, optional, default: model) — Grouping dimension. `trace` and `thread` use entity rollups.
  - Allowed values: `model`, `provider_id`, `organization_key_id`, `prompt_id`, `deployment_id`, `deployment_name`, `custom_identifier`, `customer_identifier`, `trace`, `thread`
- `sort_by` (string, optional, default: number_of_requests)
- `start_time` (datetime, optional)
- `end_time` (datetime, optional)
- `environment` (string, optional)
- `page` (integer, optional)
- `page_size` (integer, optional)

### Body (application/json)

This endpoint expects an object.

- `filters` (map from string to any, optional) — Narrows what's grouped. Each key is a field to filter on, and each value is a condition: `{"<field>": {"operator": "<operator>", "value": [...]}}`. Each span, trace or thread must match every condition. To set two conditions on one field, such as a range, pass a list of conditions. **Operators:** `""` (equals, the default), `not`, `in`, `not_in`, `lt`, `lte`, `gt`, `gte`, `contains`, `not_contains`, `icontains` (ignores case), `startswith`, `not_startswith`, `endswith`, `not_endswith`, `empty`, `not_empty`. Put values in a list: `""` and `in` match any of the listed values, and `not` and `not_in` match none of them. Other operators take one value; for `empty` and `not_empty`, send `[""]`. **Fields** depend on `group_by`: * `trace`: trace fields such as `total_cost`, `error_count`, `span_count`, `customer_identifier` and `metadata__<key>`, plus span fields such as `model`, which match a trace when any of its spans matches. * `thread`: thread fields such as `thread_identifier`, `customer_identifier`, `number_of_requests`, `total_cost` and `total_tokens`. * Any other value: span columns, such as `model`, `provider_id`, `deployment_name`, `customer_identifier`, `custom_identifier`, `organization_key_id`, `prompt_id`, `log_type`, `status_code`, `cost`, `latency`, `prompt_tokens`, `completion_tokens` and `total_request_tokens`, plus `metadata__<key>` (values are strings). Aliases such as `total_tokens` don't work. **Example:** ```json { "status_code": {"operator": "not", "value": [200]}, "metadata__plan": {"operator": "", "value": ["pro"]} } ```

## Response

### 200

Paginated groups and aggregate metrics.

- `count` (integer, required) — Number of results on this page, not the total. Request pages until `next` is null to get every result.
- `results` (list of ApiRequestLogsGroupsPostResponsesContentApplicationJsonSchemaResultsItems, required)
- `next` (string, optional, nullable)
- `previous` (string, optional, nullable)
- `current_filters` (map from string to any, optional)
- `filters_data` (map from string to any, optional)

## Errors

### 400 Bad Request Error

Unsupported group_by value. Invalid sort_by falls back to number_of_requests.

- `error` (string, required)

### 403 Forbidden Error

The API key is missing, invalid or expired, or it doesn't grant analytics read access.

- `detail` (string, required)

## Types

### ApiRequestLogsGroupsPostResponsesContentApplicationJsonSchemaResultsItems

Aggregated metrics plus the selected group key. Trace and thread groups include their richer entity fields.

- `date_group` (datetime, optional)
- `model` (string, optional)
- `provider_id` (string, optional)
- `organization_key_id` (string, optional)
- `prompt_id` (string, optional)
- `deployment_id` (string, optional)
- `deployment_name` (string, optional)
- `custom_identifier` (string, optional)
- `customer_identifier` (string, optional)
- `trace_unique_id` (string, optional)
- `thread_identifier` (string, optional)
- `number_of_requests` (integer, optional, nullable)
- `span_count` (integer, optional, nullable)
- `total_cost` (double, optional, nullable)
- `total_tokens` (integer, optional, nullable)
- `error_count` (integer, optional, nullable)
- `error_percentage` (double, optional, nullable)
- `average_cost` (double, optional, nullable)
- `average_tokens` (integer, optional, nullable)
- `average_latency` (double, optional, nullable)
- `average_ttft` (double, optional, nullable)
- `average_tps` (double, optional, nullable)
- `cache_hit_percentage` (double, optional, nullable)

## Examples

**Request**

```json
{}
```

**Response**

```json
{
  "count": 1,
  "results": [
    {
      "date_group": "2024-01-15T09:30:00Z",
      "model": "string",
      "provider_id": "string",
      "organization_key_id": "string",
      "prompt_id": "string",
      "deployment_id": "string",
      "deployment_name": "string",
      "custom_identifier": "string",
      "customer_identifier": "string",
      "trace_unique_id": "string",
      "thread_identifier": "string",
      "number_of_requests": 1,
      "span_count": 1,
      "total_cost": 1.1,
      "total_tokens": 1,
      "error_count": 1,
      "error_percentage": 1.1,
      "average_cost": 1.1,
      "average_tokens": 1,
      "average_latency": 1.1,
      "average_ttft": 1.1,
      "average_tps": 1.1,
      "cache_hit_percentage": 1.1
    }
  ],
  "next": "string",
  "previous": "string",
  "current_filters": {},
  "filters_data": {}
}
```

**SDK Code**

```python
import requests

url = "https://api.respan.ai/api/request-logs/groups/"

payload = {}
headers = {
    "Authorization": "Bearer <respanApiKey>",
    "Content-Type": "application/json"
}

response = requests.post(url, json=payload, headers=headers)

print(response.json())
```

```javascript
const url = 'https://api.respan.ai/api/request-logs/groups/';
const options = {
  method: 'POST',
  headers: {Authorization: 'Bearer <respanApiKey>', 'Content-Type': 'application/json'},
  body: '{}'
};

try {
  const response = await fetch(url, options);
  const data = await response.json();
  console.log(data);
} catch (error) {
  console.error(error);
}
```

```go
package main

import (
	"fmt"
	"strings"
	"net/http"
	"io"
)

func main() {

	url := "https://api.respan.ai/api/request-logs/groups/"

	payload := strings.NewReader("{}")

	req, _ := http.NewRequest("POST", url, payload)

	req.Header.Add("Authorization", "Bearer <respanApiKey>")
	req.Header.Add("Content-Type", "application/json")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := io.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println(string(body))

}
```

```ruby
require 'uri'
require 'net/http'

url = URI("https://api.respan.ai/api/request-logs/groups/")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Post.new(url)
request["Authorization"] = 'Bearer <respanApiKey>'
request["Content-Type"] = 'application/json'
request.body = "{}"

response = http.request(request)
puts response.read_body
```

```java
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("https://api.respan.ai/api/request-logs/groups/")
  .header("Authorization", "Bearer <respanApiKey>")
  .header("Content-Type", "application/json")
  .body("{}")
  .asString();
```

```php
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.respan.ai/api/request-logs/groups/', [
  'body' => '{}',
  'headers' => [
    'Authorization' => 'Bearer <respanApiKey>',
    'Content-Type' => 'application/json',
  ],
]);

echo $response->getBody();
```

```csharp
using RestSharp;

var client = new RestClient("https://api.respan.ai/api/request-logs/groups/");
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Bearer <respanApiKey>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift
import Foundation

let headers = [
  "Authorization": "Bearer <respanApiKey>",
  "Content-Type": "application/json"
]
let parameters = [] as [String : Any]

let postData = JSONSerialization.data(withJSONObject: parameters, options: [])

let request = NSMutableURLRequest(url: NSURL(string: "https://api.respan.ai/api/request-logs/groups/")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error as Any)
  } else {
    let httpResponse = response as? HTTPURLResponse
    print(httpResponse)
  }
})

dataTask.resume()
```