> ## Documentation Index
> Fetch the complete documentation index at: https://braintrust.dev/docs/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 specification published at [braintrust-openapi](https://github.com/braintrustdata/braintrust-openapi) on GitHub.

## Base URL

The base URL depends on your organization's [data plane region](/docs/admin/organizations#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 **<Icon icon="settings-2" /> Settings** > [**<Icon icon="lock" /> Data plane**](https://www.braintrust.dev/app/~/configuration/org/api-url).

## 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/settings?subroute=api-keys).

## SDKs

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

<CardGroup cols={2}>
  <Card title="TypeScript SDK" icon="https://mintcdn.com/braintrust/c7ni0sUjwFCk4A6a/images/sdk-icons/typescript.svg?fit=max&auto=format&n=c7ni0sUjwFCk4A6a&q=85&s=7435e9525dad7c7d78d0dc33dc4bd18d" href="/docs/sdks/typescript/quickstart" width="27" height="27" data-path="images/sdk-icons/typescript.svg">
    Official TypeScript/JavaScript SDK
  </Card>

  <Card title="Python SDK" icon="https://mintcdn.com/braintrust/c7ni0sUjwFCk4A6a/images/sdk-icons/python.svg?fit=max&auto=format&n=c7ni0sUjwFCk4A6a&q=85&s=1d27736793336d98f35e75c83f61a4ed" href="/docs/sdks/python/quickstart" width="114" height="116" data-path="images/sdk-icons/python.svg">
    Official Python SDK
  </Card>

  <Card title="Go SDK" icon="https://mintcdn.com/braintrust/c7ni0sUjwFCk4A6a/images/sdk-icons/go.svg?fit=max&auto=format&n=c7ni0sUjwFCk4A6a&q=85&s=386e50068ff16a81a72846e6699e6028" href="/docs/sdks/go/quickstart" width="27" height="27" data-path="images/sdk-icons/go.svg">
    Official Go SDK
  </Card>

  <Card title="Ruby SDK" icon="https://mintcdn.com/braintrust/c7ni0sUjwFCk4A6a/images/sdk-icons/ruby.svg?fit=max&auto=format&n=c7ni0sUjwFCk4A6a&q=85&s=e9d88fa4e89e67ad544b7538c483e31b" href="/docs/sdks/ruby/quickstart" width="27" height="27" data-path="images/sdk-icons/ruby.svg">
    Official Ruby SDK
  </Card>

  <Card title="Java SDK" icon="https://mintcdn.com/braintrust/c7ni0sUjwFCk4A6a/images/sdk-icons/java.svg?fit=max&auto=format&n=c7ni0sUjwFCk4A6a&q=85&s=59297deb5bf3df363e4d4d578bd0e34b" href="/docs/sdks/java/quickstart" width="432" height="544" data-path="images/sdk-icons/java.svg">
    Official Java SDK
  </Card>

  <Card title="C# SDK" icon="https://mintcdn.com/braintrust/c7ni0sUjwFCk4A6a/images/sdk-icons/csharp.svg?fit=max&auto=format&n=c7ni0sUjwFCk4A6a&q=85&s=83cb96c53f762aea3ffab0c821653771" href="/docs/sdks/csharp/quickstart" width="27" height="27" data-path="images/sdk-icons/csharp.svg">
    Official C# SDK
  </Card>
</CardGroup>

## 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](/docs/plans-and-limits#system-limits) for the limits that apply to all deployments, or [Set inbound request rate limits](/docs/admin/self-hosting/configure/networking#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](/docs/api-reference/query).

### Filter experiments by metadata

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

<CodeGroup dropdown>
  ```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);
  }
  ```
</CodeGroup>

## 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:

<CodeGroup dropdown>
  ```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}
              }]
          }
      )
  ```
</CodeGroup>

### Log programmatically

Insert logs via the API:

<CodeGroup dropdown>
  ```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"}
          }]
      }
  )
  ```
</CodeGroup>

### Delete logs

Mark logs for deletion by setting `_object_delete`:

<CodeGroup dropdown>
  ```python theme={"theme":{"light":"github-light","dark":"github-dark-dimmed"}} 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}
  )
  ```
</CodeGroup>

## Impersonate users

To make API requests using another user's identity and permissions, authenticate with a personal API key or [service token](/docs/admin/access-control/manage-permissions#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](/docs/admin/access-control/manage-permissions), including [service account permission groups](/docs/admin/access-control/manage-permissions#use-service-accounts). To grant a role through the API, see [Create ACL](/docs/api-reference/acls/create-acl).

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:

<CodeGroup dropdown>
  ```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"
  ```
</CodeGroup>

The response lists projects accessible to the impersonated user.

## Next steps

* Explore the [complete API reference](/docs/api-reference) for all available endpoints
* Learn about [SQL querying](/docs/reference/sql) to analyze your data
* Review [system limits](/docs/plans-and-limits) for API usage constraints
* Check out the [Python SDK](/docs/sdks/python/versions/latest) or [TypeScript SDK](/docs/sdks/typescript/versions/latest) 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)
