> ## Documentation Index
> Fetch the complete documentation index at: https://docs.debtstack.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Batch Operations

> Execute multiple API calls in one request

## Overview

Execute multiple primitive operations in a single request. Operations run in parallel for optimal performance. Useful for reducing round-trips when you need data from multiple endpoints.

## Request

<ParamField body="operations" type="array" required>
  Array of operations to execute (max 10).

  <Expandable title="properties">
    <ParamField body="primitive" type="string" required>
      The primitive to execute. See supported primitives below.
    </ParamField>

    <ParamField body="params" type="object" required>
      Parameters for the primitive (same as query params for GET endpoints).
    </ParamField>
  </Expandable>
</ParamField>

## Supported Primitives

| Primitive           | Maps To                      |
| ------------------- | ---------------------------- |
| `search.companies`  | `GET /v1/companies`          |
| `search.bonds`      | `GET /v1/bonds`              |
| `resolve.bond`      | `GET /v1/bonds/resolve`      |
| `search.pricing`    | `GET /v1/pricing`            |
| `traverse.entities` | `POST /v1/entities/traverse` |
| `search.documents`  | `GET /v1/documents/search`   |

## Response

<ResponseField name="results" type="array">
  Array of results, one per operation.

  <Expandable title="properties">
    <ResponseField name="primitive" type="string">
      The primitive that was executed.
    </ResponseField>

    <ResponseField name="status" type="string">
      `success` or `error`
    </ResponseField>

    <ResponseField name="data" type="any">
      The result data (same as individual endpoint).
    </ResponseField>

    <ResponseField name="error" type="object">
      Error details if status is `error`.
    </ResponseField>
  </Expandable>
</ResponseField>

<ResponseField name="meta" type="object">
  <Expandable title="properties">
    <ResponseField name="total_operations" type="integer">
      Number of operations requested.
    </ResponseField>

    <ResponseField name="successful" type="integer">
      Number of successful operations.
    </ResponseField>

    <ResponseField name="failed" type="integer">
      Number of failed operations.
    </ResponseField>

    <ResponseField name="duration_ms" type="integer">
      Total execution time in milliseconds.
    </ResponseField>
  </Expandable>
</ResponseField>

## Examples

### Multiple Data Types

Get company metrics and bonds in one call:

<CodeGroup>
  ```bash curl theme={null}
  curl -X POST "https://api.debtstack.ai/v1/batch" \
    -H "X-API-Key: ds_xxxxx" \
    -H "Content-Type: application/json" \
    -d '{
      "operations": [
        {
          "primitive": "search.companies",
          "params": {
            "ticker": "RIG",
            "fields": "ticker,name,net_leverage_ratio,total_debt"
          }
        },
        {
          "primitive": "search.bonds",
          "params": {
            "ticker": "RIG",
            "has_pricing": true,
            "fields": "name,cusip,maturity_date,pricing"
          }
        }
      ]
    }'
  ```

  ```python Python theme={null}
  import requests

  response = requests.post(
      "https://api.debtstack.ai/v1/batch",
      headers={
          "X-API-Key": "ds_xxxxx",
          "Content-Type": "application/json"
      },
      json={
          "operations": [
              {
                  "primitive": "search.companies",
                  "params": {
                      "ticker": "RIG",
                      "fields": "ticker,name,net_leverage_ratio,total_debt"
                  }
              },
              {
                  "primitive": "search.bonds",
                  "params": {
                      "ticker": "RIG",
                      "has_pricing": True,
                      "fields": "name,cusip,maturity_date,pricing"
                  }
              }
          ]
      }
  )

  results = response.json()["results"]
  company = results[0]["data"][0]
  bonds = results[1]["data"]

  print(f"{company['name']}: {company['net_leverage_ratio']}x leverage")
  print(f"Bonds with pricing: {len(bonds)}")
  ```
</CodeGroup>

### Response

```json theme={null}
{
  "results": [
    {
      "primitive": "search.companies",
      "status": "success",
      "data": [
        {
          "ticker": "RIG",
          "name": "Transocean Ltd.",
          "net_leverage_ratio": 4.2,
          "total_debt": 750000000000
        }
      ],
      "meta": {"total": 1}
    },
    {
      "primitive": "search.bonds",
      "status": "success",
      "data": [
        {
          "name": "8.00% Senior Notes due 2027",
          "cusip": "893830AK8",
          "maturity_date": "2027-02-01",
          "pricing": {
            "last_price": 94.25,
            "ytm": 9.42,
            "spread": 512
          }
        }
      ],
      "meta": {"total": 6}
    }
  ],
  "meta": {
    "total_operations": 2,
    "successful": 2,
    "failed": 0,
    "duration_ms": 145
  }
}
```

### Compare Multiple Companies

```python theme={null}
response = requests.post(
    f"{BASE_URL}/batch",
    headers={"X-API-Key": API_KEY, "Content-Type": "application/json"},
    json={
        "operations": [
            {
                "primitive": "search.companies",
                "params": {
                    "ticker": "RIG",
                    "fields": "ticker,name,net_leverage_ratio"
                }
            },
            {
                "primitive": "search.companies",
                "params": {
                    "ticker": "VAL",
                    "fields": "ticker,name,net_leverage_ratio"
                }
            },
            {
                "primitive": "search.companies",
                "params": {
                    "ticker": "DO",
                    "fields": "ticker,name,net_leverage_ratio"
                }
            }
        ]
    }
)

# Compare leverage across drilling companies
for result in response.json()["results"]:
    if result["status"] == "success" and result["data"]:
        company = result["data"][0]
        print(f"{company['ticker']}: {company['net_leverage_ratio']}x")
```

### Mixed Primitives

```python theme={null}
response = requests.post(
    f"{BASE_URL}/batch",
    headers={"X-API-Key": API_KEY, "Content-Type": "application/json"},
    json={
        "operations": [
            # Get company info
            {
                "primitive": "search.companies",
                "params": {"ticker": "CHTR", "fields": "ticker,name,total_debt"}
            },
            # Resolve a bond
            {
                "primitive": "resolve.bond",
                "params": {"q": "CHTR 5% 2028"}
            },
            # Search for covenant language
            {
                "primitive": "search.documents",
                "params": {
                    "q": "leverage covenant",
                    "ticker": "CHTR",
                    "section_type": "credit_agreement",
                    "limit": 3
                }
            }
        ]
    }
)
```

### Error Handling

If one operation fails, others still execute:

```json theme={null}
{
  "results": [
    {
      "primitive": "search.companies",
      "status": "success",
      "data": [...]
    },
    {
      "primitive": "resolve.bond",
      "status": "error",
      "error": {
        "code": "NOT_FOUND",
        "message": "No matching bonds found for query 'XYZ 5% 2025'"
      }
    }
  ],
  "meta": {
    "total_operations": 2,
    "successful": 1,
    "failed": 1
  }
}
```

Check status for each operation:

```python theme={null}
for result in response.json()["results"]:
    if result["status"] == "success":
        print(f"{result['primitive']}: {len(result.get('data', []))} results")
    else:
        print(f"{result['primitive']}: ERROR - {result['error']['message']}")
```

## Limits

* Maximum 10 operations per batch
* Each operation counts toward rate limits
* Credit cost is sum of individual operations

## Use Cases

### Complete Company Profile

```python theme={null}
def get_company_profile(ticker):
    """Get complete company data in one call."""
    response = requests.post(
        f"{BASE_URL}/batch",
        headers={"X-API-Key": API_KEY, "Content-Type": "application/json"},
        json={
            "operations": [
                {"primitive": "search.companies", "params": {"ticker": ticker}},
                {"primitive": "search.bonds", "params": {"ticker": ticker}},
                {"primitive": "search.pricing", "params": {"ticker": ticker}}
            ]
        }
    )

    results = response.json()["results"]
    return {
        "company": results[0]["data"][0] if results[0]["data"] else None,
        "bonds": results[1]["data"],
        "pricing": results[2]["data"]
    }
```

### Portfolio Overview

```python theme={null}
def portfolio_overview(tickers):
    """Get key metrics for multiple companies."""
    operations = [
        {
            "primitive": "search.companies",
            "params": {
                "ticker": ticker,
                "fields": "ticker,name,net_leverage_ratio,total_debt"
            }
        }
        for ticker in tickers
    ]

    response = requests.post(
        f"{BASE_URL}/batch",
        headers={"X-API-Key": API_KEY, "Content-Type": "application/json"},
        json={"operations": operations[:10]}  # Max 10
    )

    return [
        r["data"][0] for r in response.json()["results"]
        if r["status"] == "success" and r["data"]
    ]
```
