A new Python example from Telnyx demonstrates how to build a small API that translates natural language questions into SQL queries. The project, available on GitHub, uses Telnyx AI Inference to convert plain English into structured database queries, complete with validation layers for safety.
How the API Works
The Flask-based application exposes several endpoints. The primary one, `POST /query`, accepts a natural-language question, SQL dialect, and schema DDL, returning JSON with the generated SQL, explanation, tables used, and metadata. A sample endpoint (`POST /query/sample`) comes with a bundled SQLite dataset so users can test questions without connecting a production database. There is also a `POST /validate` endpoint that dry-runs a SQL string against the sample dataset.
Safety and Validation
Natural language to SQL requires guardrails. The example asks the model for read-only SQL and then checks the generated query before execution. The validation layer rejects multiple statements, comments, and write-oriented SQL keywords. This keeps the focus on a safe workflow: ask a question, include schema context, generate a query, validate it, and return structured results. The model handles language translation, while the app owns the safety checks.
Running the Example
To run it, clone the repository, create a `.env` file with a Telnyx API key, install dependencies, and start the app. Users can then send curl requests to ask questions against the sample dataset or validate custom SQL. The example is designed for internal tooling such as analytics assistants, support dashboards, sales operations tools, and data warehouse query helpers.