Query Databases from an Agent
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:
connectionsto list connections and read cached schemasqueryto execute SQL directlychatonly when the agent will ask natural-language questions
1. List connections
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
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
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:
{
"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.
Ready to try this on your own database?
Connect in minutes and ask your first question — no SQL required.
Start freeFree plan · No credit card required