Docs
SQL Generation API

SQL Generation API

API endpoint for generating SQL queries from natural language

The SQL Generation API allows you to convert natural language queries into SQL statements without executing them. This is useful for applications that need to generate SQL queries programmatically based on user input.

Endpoint

POST /faas/api/sql

Authentication

All requests must include an API key in the Authorization header:

Authorization: Bearer sk_your_api_key

API keys must start with the prefix sk_ and can be generated from your account dashboard.

Request Format

ParameterTypeDescription
userInputstringThe natural language query to convert to SQL
modelIdstringThe ID of the AI model to use for generation (see available models)
databaseIdstringThe ID of the database to generate SQL for
chatIdstring(Optional) The ID of an existing chat to associate with this query

Example Request

{
  "userInput": "Find all users who signed up in the last month",
  "modelId": "gpt-4o",
  "databaseId": "db_12345"
}

Response Format

FieldTypeDescription
chatIdstringThe ID of the chat this query is associated with (new or existing)
sqlQuerystringThe generated SQL query
errorstring | nullError message if generation failed
usageobjectToken usage information for the request
userMessageIdstringID of the saved user message
assistantMessageIdstringID of the saved assistant message

Example Response

{
  "chatId": "chat_67890",
  "sqlQuery": "SELECT * FROM users WHERE created_at >= DATE_SUB(NOW(), INTERVAL 1 MONTH);",
  "error": null,
  "usage": {
    "promptTokens": 250,
    "completionTokens": 35,
    "totalTokens": 285
  },
  "userMessageId": "msg_12345",
  "assistantMessageId": "msg_67890"
}

Error Codes

Status CodeDescription
400Invalid request format
401Missing or invalid API key
404Model or database not found
500Server error

Limitations

  • The API has a maximum duration of 60 seconds per request
  • The generated SQL is not executed against your database
  • The API only generates the SQL query based on the database schema
  • All queries and responses are saved to your chat history

Example Usage

const response = await fetch('https://app.chatdb.live/faas/api/sql', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer sk_your_api_key'
  },
  body: JSON.stringify({
    userInput: 'Show me all customers who made a purchase last week',
    modelId: 'gpt-4',
    databaseId: 'db_12345'
  })
});
 
const data = await response.json();
console.log(data.sqlQuery);