Copy
Trading Bots
Events
More

Build a Natural Language to SQL API in Python

2026/07/16 07:21Browse 0

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.

Disclaimer: This page may contain third-party information and does not necessarily reflect BYDFi's views or opinions. This content is for general reference only and does not constitute any representation, warranty, financial advice, or investment advice. BYDFi is not responsible for any errors, omissions, or any results arising from the use of such information. Virtual asset investments involve risks. Please carefully evaluate the risks of the product and your risk tolerance based on your financial situation. For more information, please refer to our Terms of Use and Risk Disclosure.