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

# API Reference

> Complete API reference for the Braintrust API

The Braintrust API allows you to interact with all aspects of the Braintrust platform programmatically. You can use it to:

* Create and manage projects, experiments, and datasets
* Log traces and metrics
* Manage prompts, tools, and scorers
* Configure access control and permissions
* Retrieve and analyze results

The API is defined by an OpenAPI 3.1.1 specification published at [braintrust-openapi](https://github.com/braintrustdata/braintrust-openapi) on GitHub. Nullable fields use the OpenAPI 3.1 form (`"type": ["string", "null"]`) rather than `nullable: true`. Client generators and other tooling that reads the spec must support OpenAPI 3.1.

## Base URL

The base URL depends on your organization's [data plane region](https://docs.braintrust.dev/admin/organizations.md#data-plane-region):

| Region | Base URL |
| - | - |
| US | `https://api.braintrust.dev` |
| EU | `https://api-eu.braintrust.dev` |
| Self-hosted | Your custom data plane URL |

You can find your API URL in ** Settings** > [** Data plane**](https://www.braintrust.dev/app/~/configuration/data-plane).

## Authentication

Authenticate requests with your API key in the Authorization header:

```bash theme={"theme":{"light":"github-light","dark":"github-dark-dimmed"}}
curl https://api.braintrust.dev/v1/project \
  -H "Authorization: Bearer $BRAINTRUST_API_KEY"
```

Create API keys in ** Settings** > [** API keys**](https://www.braintrust.dev/app/~/configuration/api-keys).

## SDKs

While you can call the API directly, we recommend using one of our official SDKs:

> [card] [TypeScript SDK](https://docs.braintrust.dev/sdks/typescript/quickstart.md)
>
> Official TypeScript/JavaScript SDK

> [card] [Python SDK](https://docs.braintrust.dev/sdks/python/quickstart.md)
>
> Official Python SDK

> [card] [Go SDK](https://docs.braintrust.dev/sdks/go/quickstart.md)
>
> Official Go SDK

> [card] [Ruby SDK](https://docs.braintrust.dev/sdks/ruby/quickstart.md)
>
> Official Ruby SDK

> [card] [Java SDK](https://docs.braintrust.dev/sdks/java/quickstart.md)
>
> Official Java SDK

> [card] [C# SDK](https://docs.braintrust.dev/sdks/csharp/quickstart.md)
>
> Official C# SDK

## API resources

The API is organized around REST principles. Each resource has predictable URLs and uses HTTP response codes to indicate API errors.

**Project resources**

* **Projects**: Organize your AI features and experiments
* **Experiments**: Run and track evaluation experiments
* **Datasets**: Manage test data for evaluations
* **Logs**: Store and query production traces
* **Prompts**: Version control your prompts
* **Functions**: Manage tools, scorers, and workflows
* **Evals**: Configure and run evaluations
* **Scores**: Define custom scoring functions
* **Tags**: Organize and filter project resources
* **Automations**: Configure automated workflows
* **Views**: Create and manage custom data views

**Organization resources**

* **Organizations**: Manage your organization settings
* **Users**: Manage team members
* **Groups**: Organize users into teams
* **Project groups**: Organize projects into groups
* **Roles**: Define permission levels
* **ACLs**: Configure fine-grained access control
* **API keys**: Manage authentication credentials
* **Service tokens**: Generate service-level authentication tokens

**Configuration resources**

* **AI secrets**: Securely store API keys and credentials
* **Environment variables**: Manage environment-specific configuration
* **MCP servers**: Configure Model Context Protocol servers
* **Proxy**: Configure proxy settings for API requests

## Response format

All API responses are returned in JSON format. Successful responses will have a `2xx` status code, while errors will return `4xx` or `5xx` status codes with error details.

## Rate limits

The API uses rate limiting to ensure fair usage. Rate limits are applied per endpoint and are scoped to an organization, a project, or both. If you exceed the rate limit, you'll receive a `429 Too Many Requests` response. See [system limits](https://docs.braintrust.dev/plans-and-limits.md#system-limits) for the limits that apply to all deployments, or [Set inbound request rate limits](https://docs.braintrust.dev/admin/self-hosting/configure/networking.md#set-inbound-request-rate-limits) to configure them on a self-hosted deployment.

## Query data

Query your logs, experiments, and datasets with SQL through the `/btql` endpoint. For a full reference, see [Query by SQL](https://docs.braintrust.dev/api-reference/query.md).

### Filter experiments by metadata

Filter experiments by metadata field equality using the `metadata` query parameter on [`GET /v1/experiment`](https://docs.braintrust.dev/api-reference/experiments/get-experiment). Pass a JSON-serialized object to match experiments where all specified fields are equal, including nested paths:

```python theme={"theme":{"light":"github-light","dark":"github-dark-dimmed"}}
import json
import os
import requests

API_URL = "https://api.braintrust.dev/v1"
headers = {"Authorization": "Bearer " + os.environ["BRAINTRUST_API_KEY"]}

response = requests.get(
    f"{API_URL}/experiment",
    headers=headers,
    params=dict(
        project_id="your-project-id",
        metadata=json.dumps({"env": "production", "model": {"name": "gpt-5-mini"}}),
    ),
)

experiments = response.json().get("objects", [])
for experiment in experiments:
    print(experiment["id"], experiment["name"])
```

```typescript theme={"theme":{"light":"github-light","dark":"github-dark-dimmed"}}
const API_URL = "https://api.braintrust.dev/v1";
const headers = {
  Authorization: `Bearer ${process.env.BRAINTRUST_API_KEY}`,
};

const params = new URLSearchParams({
  project_id: "your-project-id",
  metadata: JSON.stringify({ env: "production", model: { name: "gpt-5-mini" } }),
});

const response = await fetch(`${API_URL}/experiment?${params}`, { headers });
const { objects: experiments } = await response.json();
for (const experiment of experiments) {
  console.log(experiment.id, experiment.name);
}
```

## Invoke functions

Call prompts, tools, or scorers via the `/v1/function` endpoint:

```bash theme={"theme":{"light":"github-light","dark":"github-dark-dimmed"}}
curl https://api.braintrust.dev/v1/function \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $BRAINTRUST_API_KEY" \
  -d '{
    "project_name": "My Project",
    "slug": "summarizer",
    "input": {
      "text": "Long text to summarize..."
    }
  }'
```

**Parameters**

* `project_name` or `project_id`: Project containing the function
* `slug`: Function slug
* `input`: Function input parameters
* `version` (optional): Pin to a specific version
* `environment` (optional): Use environment-specific version
* `stream` (optional): Enable streaming responses

**Response**

```json theme={"theme":{"light":"github-light","dark":"github-dark-dimmed"}}
{
  "output": "Summarized text here...",
  "metadata": {
    "model": "claude-3-5-sonnet-latest",
    "tokens": 150,
    "latency": 0.85
  }
}
```

## Write and manage data

### Run experiments

Create and run experiments programmatically:

```python theme={"theme":{"light":"github-light","dark":"github-dark-dimmed"}}
import os
from uuid import uuid4
import requests

API_URL = "https://api.braintrust.dev/v1"
headers = {"Authorization": "Bearer " + os.environ["BRAINTRUST_API_KEY"]}

# Create a project
project = requests.post(
    f"{API_URL}/project",
    headers=headers,
    json={"name": "My Project"}
).json()

# Create an experiment
experiment = requests.post(
    f"{API_URL}/experiment",
    headers=headers,
    json={"name": "Test Run", "project_id": project["id"]}
).json()

# Insert experiment results
for i in range(10):
    requests.post(
        f"{API_URL}/experiment/{experiment['id']}/insert",
        headers=headers,
        json={
            "events": [{
                "id": uuid4().hex,
                "input": {"question": f"Test {i}"},
                "output": f"Answer {i}",
                "scores": {"accuracy": 0.9}
            }]
        }
    )
```

### Log programmatically

Insert logs via the API:

```python theme={"theme":{"light":"github-light","dark":"github-dark-dimmed"}}
import os
from uuid import uuid4
import requests

API_URL = "https://api.braintrust.dev/v1"
headers = {"Authorization": "Bearer " + os.environ["BRAINTRUST_API_KEY"]}

# Get or create project
project = requests.post(
    f"{API_URL}/project",
    headers=headers,
    json={"name": "My Project"}
).json()

# Insert log event
requests.post(
    f"{API_URL}/project_logs/{project['id']}/insert",
    headers=headers,
    json={
        "events": [{
            "id": uuid4().hex,
            "input": {"question": "What is 2+2?"},
            "output": "4",
            "scores": {"accuracy": 1.0},
            "metadata": {"environment": "production"}
        }]
    }
)
```

### Delete logs

Mark logs for deletion by setting `_object_delete`:

```python theme={"theme":{"light":"github-light","dark":"github-dark-dimmed"}}
import os
import requests

API_URL = "https://api.braintrust.dev/"
headers = {"Authorization": "Bearer " + os.environ["BRAINTRUST_API_KEY"]}

# Find logs to delete
query = """
SELECT id
FROM project_logs('project-id', shape => 'traces')
WHERE metadata.user_id = 'test-user'
"""

response = requests.post(
    f"{API_URL}/btql",
    headers=headers,
    json={"query": query}
).json()

ids = [row["id"] for row in response["data"]]

# Delete logs
delete_events = [{"id": id, "_object_delete": True} for id in ids]
requests.post(
    f"{API_URL}/v1/project_logs/project-id/insert",
    headers=headers,
    json={"events": delete_events}
)
```

## Impersonate users

To make API requests using another user's identity and permissions, authenticate with a personal API key or [service token](https://docs.braintrust.dev/admin/access-control/manage-permissions.md#use-service-accounts) and set the `x-bt-impersonate-user` header to the target user's email or user ID.

Braintrust requires that:

* The authenticating user or service account must have the `Owner` role in every organization the target user belongs to, through a direct role grant or membership in a permission group with that role. The `Manage settings` permission alone is not sufficient.
* The target user must belong to at least one organization.

For service tokens, Braintrust checks the service account's permissions, not the permissions of the person who created the token. To configure access, see [Manage permissions](https://docs.braintrust.dev/admin/access-control/manage-permissions.md), including [service account permission groups](https://docs.braintrust.dev/admin/access-control/manage-permissions.md#use-service-accounts). To grant a role through the API, see [Create ACL](https://docs.braintrust.dev/api-reference/acls/create-acl.md).

To list projects as the target user, set `BRAINTRUST_API_KEY` to your personal API key or service token, and `USER_EMAIL` to the target user's email. For self-hosted deployments, replace `https://api.braintrust.dev` with your deployment's Universal API URL:

```typescript theme={"theme":{"light":"github-light","dark":"github-dark-dimmed"}}
const apiKey = process.env.BRAINTRUST_API_KEY;
const userEmail = process.env.USER_EMAIL;

if (!apiKey || !userEmail) {
  throw new Error("Set BRAINTRUST_API_KEY and USER_EMAIL before running this example.");
}

const response = await fetch("https://api.braintrust.dev/v1/project", {
  headers: {
    Authorization: `Bearer ${apiKey}`,
    "x-bt-impersonate-user": userEmail,
  },
});

if (!response.ok) {
  throw new Error(await response.text());
}

console.log(await response.json());
```

```python theme={"theme":{"light":"github-light","dark":"github-dark-dimmed"}}
import os
import requests

response = requests.get(
    "https://api.braintrust.dev/v1/project",
    headers={
        "Authorization": f"Bearer {os.environ['BRAINTRUST_API_KEY']}",
        "x-bt-impersonate-user": os.environ["USER_EMAIL"],
    },
)
response.raise_for_status()
print(response.json())
```

```bash theme={"theme":{"light":"github-light","dark":"github-dark-dimmed"}}
curl https://api.braintrust.dev/v1/project \
  -H "Authorization: Bearer $BRAINTRUST_API_KEY" \
  -H "x-bt-impersonate-user: $USER_EMAIL"
```

The response lists projects accessible to the impersonated user.

## Next steps

* Explore the [complete API reference](https://docs.braintrust.dev/api-reference.md) for all available endpoints
* Learn about [SQL querying](https://docs.braintrust.dev/reference/sql.md) to analyze your data
* Review [system limits](https://docs.braintrust.dev/plans-and-limits.md) for API usage constraints
* Check out the [Python SDK](https://docs.braintrust.dev/sdks/python/versions/latest.md) or [TypeScript SDK](https://docs.braintrust.dev/sdks/typescript/versions/latest.md) documentation

## Support

Need help with the API?

* Join our [Discord community](https://discord.gg/6G8s47F44X)
* Email us at [support@braintrust.dev](mailto:support@braintrust.dev)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.