SQL Generation API Documentation

This API allows you to convert natural language to SQL queries, validate SQL statements, and manage your database schemas.

Authentication: All API requests require an API key to be sent in the X-API-Key header. You can manage your API keys in your dashboard.

Rate Limits

API calls are subject to rate limiting based on your subscription plan:

The API response includes the following rate limit headers:

API Endpoints

POST /api/sql/generate

Convert natural language to a SQL query. Optionally provide a database schema for better results.

Request Parameters

Parameter Type Required Description
text string Yes Natural language query to convert to SQL
dialect string No SQL dialect (standard, mysql, postgres, sqlserver, snowflake). Default: standard
schemaId string No ID of a stored schema to use for generation
prettify boolean No Format the SQL for readability. Default: false

Example

JavaScript
Python
PHP

const axios = require('axios');

async function generateSql() {
  try {
    const response = await axios.post('https://api.example.com/api/sql/generate', {
      text: 'Find all customers who placed an order in the last 30 days',
      dialect: 'mysql',
      prettify: true
    }, {
      headers: {
        'X-API-Key': 'your_api_key',
        'Content-Type': 'application/json'
      }
    });
    
    console.log(response.data);
  } catch (error) {
    console.error('Error:', error.response ? error.response.data : error.message);
  }
}

generateSql();
                

import requests

def generate_sql():
    url = 'https://api.example.com/api/sql/generate'
    headers = {
        'X-API-Key': 'your_api_key',
        'Content-Type': 'application/json'
    }
    data = {
        'text': 'Find all customers who placed an order in the last 30 days',
        'dialect': 'mysql',
        'prettify': True
    }
    
    response = requests.post(url, json=data, headers=headers)
    
    if response.status_code == 200:
        print(response.json())
    else:
        print(f"Error: {response.status_code}")
        print(response.json())

generate_sql()
                

 'Find all customers who placed an order in the last 30 days',
    'dialect' => 'mysql',
    'prettify' => true
];

$options = [
    'http' => [
        'method' => 'POST',
        'header' => [
            'Content-Type: application/json',
            'X-API-Key: your_api_key'
        ],
        'content' => json_encode($data)
    ]
];

$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);

if ($response !== false) {
    $result = json_decode($response, true);
    print_r($result);
} else {
    echo "Error making request to API";
}
?>
                

Response


{
  "sql": "
  SELECT 
    c.customer_id,
    c.first_name,
    c.last_name,
    c.email
  FROM customers c
  JOIN orders o ON c.customer_id = o.customer_id
  WHERE o.order_date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)
  GROUP BY c.customer_id",
  "type": "SELECT",
  "execution_time": 345
}
            

POST /api/sql/validate

Validate a SQL query, optionally against a stored schema.

Request Parameters

Parameter Type Required Description
sql string Yes SQL query to validate
schemaId string No ID of a stored schema to validate against

Example

JavaScript
Python
PHP

const axios = require('axios');

async function validateSql() {
  try {
    const response = await axios.post('https://api.example.com/api/sql/validate', {
      sql: 'SELECT customer_id, name FROM customers WHERE signup_date > "2023-01-01"',
      schemaId: 'your_schema_id'
    }, {
      headers: {
        'X-API-Key': 'your_api_key',
        'Content-Type': 'application/json'
      }
    });
    
    console.log(response.data);
  } catch (error) {
    console.error('Error:', error.response ? error.response.data : error.message);
  }
}

validateSql();
                

import requests

def validate_sql():
    url = 'https://api.example.com/api/sql/validate'
    headers = {
        'X-API-Key': 'your_api_key',
        'Content-Type': 'application/json'
    }
    data = {
        'sql': 'SELECT customer_id, name FROM customers WHERE signup_date > "2023-01-01"',
        'schemaId': 'your_schema_id'
    }
    
    response = requests.post(url, json=data, headers=headers)
    
    if response.status_code == 200:
        print(response.json())
    else:
        print(f"Error: {response.status_code}")
        print(response.json())

validate_sql()
                

 'SELECT customer_id, name FROM customers WHERE signup_date > "2023-01-01"',
    'schemaId' => 'your_schema_id'
];

$options = [
    'http' => [
        'method' => 'POST',
        'header' => [
            'Content-Type: application/json',
            'X-API-Key: your_api_key'
        ],
        'content' => json_encode($data)
    ]
];

$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);

if ($response !== false) {
    $result = json_decode($response, true);
    print_r($result);
} else {
    echo "Error making request to API";
}
?>
                

Response


{
  "valid": true,
  "type": "SELECT",
  "error": null,
  "execution_time": 12
}
            

POST /api/sql/schema

Create or update a database schema for use with SQL generation.

Request Parameters

Parameter Type Required Description
name string Yes Schema name
description string No Schema description
content object Yes JSON representation of database schema

Schema Format


{
  "tables": [
    {
      "name": "customers",
      "columns": [
        { "name": "customer_id", "type": "INT", "constraints": "PRIMARY KEY" },
        { "name": "first_name", "type": "VARCHAR(50)", "constraints": "NOT NULL" },
        { "name": "last_name", "type": "VARCHAR(50)", "constraints": "NOT NULL" },
        { "name": "email", "type": "VARCHAR(100)", "constraints": "UNIQUE" },
        { "name": "signup_date", "type": "DATE" }
      ]
    },
    {
      "name": "orders",
      "columns": [
        { "name": "order_id", "type": "INT", "constraints": "PRIMARY KEY" },
        { "name": "customer_id", "type": "INT", "constraints": "FOREIGN KEY" },
        { "name": "order_date", "type": "DATETIME", "constraints": "NOT NULL" },
        { "name": "status", "type": "VARCHAR(20)" },
        { "name": "total_amount", "type": "DECIMAL(10,2)" }
      ]
    }
  ]
}
            

Error Responses

All API errors follow a consistent format:


{
  "error": "Error type",
  "message": "Detailed error message"
}
        

Common Error Codes

Status Code Error Type Description
400 Missing required parameter A required parameter is missing from the request
401 API key is required No API key was provided
401 Invalid or inactive API key The provided API key is invalid or has been deactivated
404 Schema not found The specified schema does not exist
429 Rate limit exceeded You have reached your monthly API call limit
500 Various Internal server error

For additional support or questions, please contact us at support@example.com.