---
title: "Query Databases from an Agent - Documentation"
description: "Discover sanitized connections and schemas, then return raw query results to an AI agent through the REST API."
canonical: "https://www.aifordatabase.com/docs/agent-querying-databases/"
---

# Query Databases from an Agent

intermediate 7 min read

## Query Databases from an Agent

This guide gives an agent the minimum safe path from connection discovery to structured database results. The public API returns connection metadata and query output, but never returns the stored database password.

### Required scopes

Use an `afd_` API key with:

*   `connections` to list connections and read cached schemas
*   `query` to execute SQL directly
*   `chat` only when the agent will ask natural-language questions

### 1\. List connections

```bash
curl https://app.aifordatabase.com/api/v1/connections?page=1&pageSize=20 \
  -H "Authorization: Bearer afd_your_key"
```

The response contains sanitized metadata including connection type, host, database name, health state, and schema timestamps. It never contains the password or encrypted credential fields.

### 2\. Read the cached schema

```bash
curl https://app.aifordatabase.com/api/v1/connections/CONNECTION_ID/schema \
  -H "Authorization: Bearer afd_your_key"
```

Use the cached schema to identify tables, columns, and relationships. To refresh it after a database change, call the same path with `POST`.

### 3\. Execute read-only SQL

```bash
curl -X POST \
  https://app.aifordatabase.com/api/v1/connections/CONNECTION_ID/query \
  -H "Authorization: Bearer afd_your_key" \
  -H "Content-Type: application/json" \
  -d '{"sql":"SELECT id, email, created_at FROM users ORDER BY created_at DESC LIMIT 5"}'
```

A successful response returns:

```json
{
  "data": {
    "columns": ["id", "email", "created_at"],
    "rows": [],
    "rowCount": 0,
    "executionTime": 18
  },
  "error": null,
  "meta": {
    "requestId": "uuid",
    "timestamp": "2026-08-04T10:00:00.000Z"
  }
}
```

### Natural-language alternative

Call `POST /api/v1/chat` with a question and `connectionId` when you want AI for Database to generate SQL. Use direct SQL when your agent already has a reviewed query or needs deterministic row shaping for a downstream API.

### Connection health

Connection reads include `lastError` and `lastErrorDiagnosis`. Check those fields before repeatedly testing an unhealthy connection. A successful first connection test also introspects and caches its schema.

NoteDatabase connections come from one fixed address, 78.47.77.162. If the user's database restricts source IPs, tell them to allow that address (in a security group, authorized networks, Atlas Network Access, or pg\_hba.conf) rather than opening the database to everyone.

Source: https://www.aifordatabase.com/docs/agent-querying-databases/
