Query Databases from an Agent

intermediate7 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.

NoteThe hosted product uses dynamic serverless egress IPs. Do not design an integration that depends on one permanent AI for Database IP address.

Ready to try this on your own database?

Connect in minutes and ask your first question — no SQL required.

Start free

Free plan · No credit card required