Turn SQL into governed REST APIs over MySQL, PostgreSQL, ClickHouse, SQLite, DuckDB, H2, MongoDB, and Parquet/CSV/JSON files - JSON, CSV, Parquet or Excel out, with scoped keys, an admin Console and MCP for AI agents.
pip install queryapigate==0.22.1 Copy PIP instructions
QueryAPIGate was previously named SQL2API. Upgrading? See Upgrading from SQL2API for what changed.
Every feature, one by one: the full walkthrough (6 minutes, in chapters)
QueryAPIGate is a self-hosted service that runs SQL against your databases - and against Parquet, CSV and JSON files on disk, S3, GCS or the web, through DuckDB - and returns the results as JSON, NDJSON, XML, YAML, CSV, TSV, Excel or Parquet. Save a query once and it becomes a versioned endpoint with typed, injection-safe parameters and run history - without writing a controller, a repository layer, pagination, auth or serialization boilerplate for it.
Write SQL. Configure the query. Apply access controls. Get an API.
$ curl 'http://127.0.0.1:5000/q/example_film_search?text=Harbor&page_size=2' -H 'X-API-Key: demo-key' [{"film_id":48,"title":"Broken Harbor","category":"Action","rating":"PG-13"},{"film_id":44,"title":"Electric Harbor","category":"Documentary","rating":"G"}] $ curl 'http://127.0.0.1:5000/q/example_top_films?top_n=2&category=Comedy&format=csv' -H 'X-API-Key: demo-key' title,category,rating,rentals,rank Electric Signal,Comedy,PG,977,1 Crimson Garden,Comedy,PG-13,631,2 The built-in Console at /console: write SQL with completion and a schema browser, run it, then save it as an API - no separate tool to install.
Home: live totals, what needs attention, recent activity, and every recent request - saved APIs and ad-hoc SQL alike.
Organizations often have valuable SQL sitting inside reports, BI dashboards, ETL pipelines, ad-hoc analysis and application code, with no path to a REST endpoint except writing a backend service around it.
SQL Query | v +------------------+ | QueryAPIGate | | | | Parameters | | SQL Guard | | Permissions | | Rate Limiting | | Caching | | Connection Pool | | Streaming | | Observability | +--------+---------+ | v REST API | +--------+--------+ v v v JSON CSV XLSX If you already know SQL, you can produce a governed API without building an API application around it.
┌──────────────────────────┐ │ QueryAPIGate │ │ │ │ Governed Data Layer │ └────────────┬─────────────┘ │ ┌───────────────────┼──────────────────┐ │ │ │ DATA ACCESS GOVERNANCE DATA DELIVERY │ │ │ Saved Queries API Keys REST APIs SQL / Mongo Roles JSON/CSV Multi-DB Collections Streaming DuckDB/files Permissions CLI exports JDBC Rate limits cron/K8s │ IP controls │ Audit │ └───────────────────┬──────────────────┘ │ OBSERVABILITY │ Metrics / Logs / History OpenAPI / Postman / UI Key features Multi-database support Tier 1 - PostgreSQL, MySQL, SQLite, DuckDB and ClickHouse: every feature, tested against a real server in CI, and covered by the compatibility promise. Experimental - H2, generic JDBC (Oracle, SQL Server, DB2, Snowflake and anything else with a driver jar) and MongoDB (find() queries): they work, with documented gaps. The same guard, pooling, parameter binding and output formats - JSON, NDJSON, XML, YAML, CSV, TSV, Excel and Parquet - apply to every one. What each supports - read-only enforcement, time limits, allowed_tables, schema browsing, streaming - is in the support matrix.
Files as a source - through DuckDB, Parquet, CSV and JSON files on local disk, S3, GCS, R2 or the web are queried where they are and published like any table, limited to the paths each connection lists (see publishing a bucket as an API).
QueryAPIGate is built to expose specific query results, not database credentials:
API Consumer | | API Key v QueryAPIGate | +-- Authentication +-- Authorization (connections + saved queries) +-- SQL guard +-- Rate limiting +-- Execution | v Database This lets an organization hand an external client a key that can only ever reach one named query - never arbitrary SQL and never a whole connection - while internal callers keep broader, connection-level access.
A saved query bundles SQL, name, description, parameters, author, version, permissions and (optionally) cache configuration into one addressable resource: GET /q/ . Saving again under the same name creates a new version rather than overwriting the old one, so a change to the SQL doesn't silently change what's already live; ?version=1 still runs the prior one, and each run is recorded in the query's execution history.
SELECT * FROM film WHERE film_id = :id GET /q/film_by_id?id=7 Values are sent to the database separately from the SQL text, so they cannot be injected into it. Parameters can declare a type, default, required/optional, enum, numeric range, length and pattern - invalid input is rejected with a field-by-field 400 before it reaches the database.
JSON, NDJSON, XML, YAML, CSV, TSV, XLSX and Parquet are all available per request (?format=), so the same saved query serves application clients, reporting and data pipelines - a Parquet export keeps column types and is typically a quarter of the CSV's size.
?page=2&page_size=50 pages results with X-Has-More telling the caller whether more exist. For full exports, ?stream=true&format=csv (or tsv/ndjson) streams the entire result straight from the database cursor rather than buffering it - verified end-to-end with 1,000,000-row results and flat server memory throughout (MySQL, PostgreSQL and ClickHouse); see Streaming exports for the measured numbers. queryapigate export --out '/exports/{name}_{date}.csv' wraps the same streaming path as a CLI command for cron/systemd/Kubernetes CronJob to call directly - no server needs to be running; see Scheduled exports to a file.
Saved queries can opt into HTTP-level caching: cache_ttl, Cache-Control, ETag, conditional requests and 304 Not Modified, plus an X-Cache: HIT/MISS header. Never applied to a query that writes.
A server-wide, IP-keyed limit (QUERYAPIGATE_RATE_LIMIT) and an independent, optional per-key limit can both be in effect at once - a request has to pass both. This lets different API consumers get different budgets:
Internal dashboard -> generous server-wide limit, no per-key limit Partner key -> 200/hour of its own Trial key -> 20/hour of its own Observability Structured JSON logs (QUERYAPIGATE_JSON_LOGS) tagged with a request ID, per-query execution timing, slow-query warnings (QUERYAPIGATE_SLOW_QUERY_THRESHOLD), and Prometheus metrics at /metrics covering request/query counts and latencies, connection-pool occupancy and rate-limit rejections.
/openapi.json is a complete, valid OpenAPI 3.0 document (checked in CI against the official validator) with every saved query listed as its own typed endpoint; /docs serves it through Swagger UI. A key's endpoint list is filtered to what that key can actually reach, so a query-scoped external key sees only its approved queries.
A built-in UI at /console covers the whole workflow: connection management, a SQL editor with syntax highlighting and schema browsing (click a table/column to insert it), query execution and preview, EXPLAIN, saved-query and version management, API key management, an audit log of administrative changes, per-query execution history, response inspection with a collapsible JSON tree for non-tabular results, a quick bar chart of any numeric result, and one-click "copy as curl" / "copy as TSV" for any result.
The UI has a collapsible sidebar (Data, Access, Observability; Ctrl+B toggles it) and a read-only Settings screen that shows every environment variable, its effective value and whether it was set or is the default (secrets are reported as configured or not, never shown), with a "Copy as .env" button. Theme, table density and the default result format are per-browser preferences.
Connect Database | v Write SQL | v Test Query | v Save Query | v Configure Access | v Expose API Testing and quality Unit tests, integration tests against real MySQL, PostgreSQL, ClickHouse and H2 servers (run in CI against service containers), DuckDB integration tests that run unconditionally since it's embedded, SQL-guard fuzz testing with Hypothesis, static type checking with mypy, linting with ruff, and CI on every push. See Development below.
+---------------------+ | API Client | +----------+----------+ | v +---------------------+ | QueryAPIGate | | | | Authentication | | Authorization | | Rate Limiting | | SQL Guard | | Parameter Binding | +----------+----------+ | v +---------------------+ | Query Manager | | | | Saved Queries | | Versions | | Cache | | API Metadata | +----------+----------+ | v +---------------------+ | Database Abstraction| | | | MySQL | | PostgreSQL | | ClickHouse | | SQLite | | H2 | | DuckDB | | JDBC | +----------+----------+ | v Database Best use cases Internal data APIs. Expose internal data to web apps, mobile apps, internal tools and other engineering teams without building a service per query:
GET /q/film_by_id?id=7 GET /q/example_top_films?top_n=5&category=Comedy Reporting APIs. Turn an existing analytical SQL report into a reusable endpoint that dashboards or scheduled jobs can call directly, in JSON or as a CSV/XLSX export.
Partner and external-client integrations. Give a partner an API key scoped to a curated list of saved queries, with its own rate limit and expiry, instead of database credentials:
Partner --API Key--> QueryAPIGate --queries grant--> Database Data engineering to application engineering. Data teams write and version the SQL; application teams consume it as a normal REST endpoint, without either side depending on the other's deploy cycle.
Data export. Stream large results as CSV, TSV, XLSX, JSON or NDJSON without loading the whole result into memory first.
Rapid prototyping. Get a working, parameterized API around an existing query for a proof of concept or internal tool without standing up a backend application for it.
QueryAPIGate's primary abstraction is the SQL query as an API resource, not the schema as a whole - so it fits well when an API should expose one specific, curated query rather than automatically surface an entire database.
Your database already contains the data logic. The goal isn't to replace application backends; it's to remove repetitive boilerplate when the actual requirement is "expose this query safely as an API" - existing SQL, plus governance, is the API.
pip install "queryapigate[postgres]" # pick the drivers you need: mysql, postgres, clickhouse, h2, duckdb # or everything: pip install "queryapigate[all]" SQLite needs no extra driver. H2 and generic JDBC connections (queryapigate[h2]) also need a Java runtime; H2's own driver jar is bundled, a JDBC connection to another vendor brings its own. DuckDB (queryapigate[duckdb]) needs no external runtime either - it's a native Python extension, same as SQLite. queryapigate[encryption] adds encryption at rest for connection passwords - only needed if you set QUERYAPIGATE_SECRET_KEY. From a clone: pip install -e ".[dev]". Or use Docker - see below.
Fastest: queryapigate examples load && queryapigate serve installs four worked example APIs (reporting, dashboard, export, partner) you can try, and queryapigate examples unload removes them again. Loading them creates a real API key per scenario, which also means the server now requires a key for every request - set QUERYAPIGATE_API_KEY yourself first so you have an admin key on hand for ad-hoc SQL too:
QUERYAPIGATE_API_KEY=demo-key queryapigate examples load # also prints one scoped key per scenario - store them now QUERYAPIGATE_API_KEY=demo-key queryapigate serve # http://127.0.0.1:5000 The examples come with a small generated examples database (films, customers and rentals), so you can also run ad-hoc SQL straight away:
curl -X POST 'http://127.0.0.1:5000/execute_sql?page_size=3' -H 'X-API-Key: demo-key' -H 'Content-Type: application/json' \ -d '{"sql": "SELECT film_id, title, rating FROM film WHERE film_id > :min", "params": {"min": 10}, "connection_name": "examples"}' Open http://127.0.0.1:5000/docs for the interactive API reference, or http://127.0.0.1:5000/console for the admin UI to manage connections and saved queries and run ad-hoc SQL without leaving the browser.
For your own databases, run queryapigate init in an empty folder: it creates queryapigate.db with an inactive template connection for every supported database type. Edit them (admin UI, or PATCH /api/v1/connections/ ), set "active": true, and start the server there.
This uses the examples connection that queryapigate examples load sets up:
curl -X POST http://127.0.0.1:5000/api/v1/queries -H 'X-API-Key: demo-key' -H 'Content-Type: application/json' -d '{ "name": "film_by_id", "sql": "SELECT * FROM film WHERE film_id = :id", "parameters": {"id": {"type": "int", "min": 1, "max": 60, "description": "Film id"}}, "connection_name": "examples", "author": "me", "description": "Look up a film", "publish": true }' curl 'http://127.0.0.1:5000/q/film_by_id?id=7&format=yaml' -H 'X-API-Key: demo-key' curl 'http://127.0.0.1:5000/q/film_by_id?id=0' -H 'X-API-Key: demo-key' # {"error": "Invalid parameters: id must be at least 1", "errors": {"id": "must be at least 1"}} Rules: type (int, float, str, bool), default, required, enum, min/max, min_length/max_length, pattern and description - see the API reference.
POST /api/v1/queries/film_by_id/versions adds version 2 - a draft until published ("publish": true, or POST .../publish); DELETE /api/v1/queries/film_by_id/versions/1 removes one version.
Add "cache_ttl": 60 to cache a response for that many seconds (X-Cache: HIT/MISS, ETag, Cache-Control) - opt-in, and never used for a query that writes. See Response caching.
Everything is configured through environment variables (all optional):
QueryAPIGate runs whatever SQL it is given against your databases, so it ships locked down and expects you to finish the job:
See documentation/THREAT_MODEL.md for the reasoning behind these controls - what's actually defended against and where it stops - and SECURITY.md to report a vulnerability.
Browsers refuse cross-origin JSON calls unless the server allows them. List the sites that may call the API:
QUERYAPIGATE_API_KEY=change-me QUERYAPIGATE_CORS_ORIGINS=https://app.example.com queryapigate serve Preflight checks are answered automatically, and the pagination headers (X-Has-More etc.) are exposed to the page's JavaScript. CORS only tells the browser which sites may call; it is not authentication, so keep the API key. Avoid * without a key: any website a visitor opens could then reach your databases through their browser (the server logs a warning if you start that way).
QUERYAPIGATE_RATE_LIMIT=60/minute gives each client address a bucket of 60 requests that refills steadily, so short bursts work but the sustained rate is capped. Over the limit, requests get 429 with a Retry-After header, and every response carries X-RateLimit-Limit and X-RateLimit-Remaining. The limit is applied before the API key check, so guessing keys is throttled too; /health and CORS preflights are never counted. With QUERYAPIGATE_REDIS_URL set, limits are counted in Redis - one budget per client address and per key across every instance and process (serve, mcp, events); if Redis fails, each process falls back to counting on its own until it's back, and an alert says so. Without Redis, state is per process: with several workers or instances, the effective limit is multiplied by their number.
An API key can also carry its own rate_limit (same grammar), checked in addition to the server-wide limit, never instead of it - a request has to pass both. See Per-key rate limiting.
Every release is published to GitHub Container Registry for linux/amd64 and linux/arm64:
docker run -p 5000:5000 -v queryapigate-data:/data -e QUERYAPIGATE_API_KEY=change-me ghcr.io/anantharajuc/queryapigate:latest Tag Contents X.Y.Z, latest QueryAPIGate with every optional feature: the PostgreSQL, MySQL, ClickHouse, DuckDB and MongoDB drivers (SQLite is built in), allowed_tables, password encryption, JWT, the Redis cache and queryapigate mcp X.Y.Z-h2, latest-h2 The same plus Java and the H2 driver - also the variant to use for a generic jdbc connection (mount your vendor's jar) The container keeps queryapigate.db in /data (create a starter with docker run --rm -v queryapigate-data:/data ghcr.io/anantharajuc/queryapigate queryapigate init). The named volume above works out of the box. To use a folder on the host instead (-v "$PWD/data:/data"), create it yourself first (mkdir data) and make sure it is writable by uid 1000, the container's user - a folder that Docker creates for you is owned by root, which the container cannot write to (or run with --user "$(id -u):$(id -g)"). It runs as a non-root user under gunicorn with one worker (each process keeps its own /metrics; scale out with more containers - see Scaling out and the reference deployment) and a health check on /health. Behind a reverse proxy or load balancer, set QUERYAPIGATE_TRUST_PROXY=1. To build it yourself: docker build -t queryapigate . (add --build-arg WITH_H2=true for H2).
For a real deployment - TLS via a reverse proxy, secrets in an env file, backups, Prometheus/Grafana - see documentation/DEPLOYMENT.md.
docker-compose.yml starts QueryAPIGate in front of a PostgreSQL database seeded with sample films:
docker compose up --build curl -H 'X-API-Key: demo-key' 'http://127.0.0.1:5000/q/films_by_rating?rating=PG&max_length=90' Open http://127.0.0.1:5000/docs, paste demo-key into the box at the top, and both saved queries appear as endpoints. The demo listens on localhost only. Once the server is healthy, a one-shot seed container (demo/seed.sh) creates the connection - its password stored as a reference to an environment variable, ${DEMO_DB_PASSWORD} - and the two saved queries through the Management API, the same calls the Console makes. Clean up with docker compose down -v.
Full details are in documentation/API.md. Saved queries can also be reached as MCP tools for an AI agent - see documentation/MCP.md.
npx @openapitools/openapi-generator-cli generate \ -i http://127.0.0.1:5000/openapi.json -g java -o clients/java # or: -g typescript-fetch, -g go, -g python, ... This is deliberately not something QueryAPIGate ships pre-generated: the spec already includes every saved query as its own typed /q/ endpoint (see Quick start above), so a client generated against your server reflects your saved queries, not a generic snapshot.
pip install -e ".[dev]" ruff check . mypy queryapigate python -m unittest discover -s tests -t . The integration tests in tests/test_integration.py run against real MySQL, PostgreSQL, ClickHouse and H2 servers when the matching QUERYAPIGATE_IT_* variables are set, and are skipped otherwise; CI runs them against service containers. DuckDB's integration tests need no such variable - being embedded, they run unconditionally whenever the duckdb package is installed. tests/test_sql_guard_fuzz.py fuzzes the SQL guard and parameter binder with Hypothesis. See CONTRIBUTING.md for the pull request process, CHANGELOG.md for what changed, and BACKLOG.md for what's planned, in priority order.
Full documentation covers installation, configuration, database connections (including JDBC and DuckDB), saved queries and parameters, authentication and authorization, API keys, rate limiting, caching, streaming, OpenAPI, metrics, the admin UI, security and deployment. Start at the documentation site or the documentation/ directory in this repo.
See BACKLOG.md for the full, prioritized list with rationale. Next is 1.0: a release candidate that freezes the REST and management APIs, the CLI, settings, error codes and the store, followed by 1.0.0. After that, all additive:
Contributions are welcome - database drivers, security, performance, UI, documentation, testing and observability are all useful areas. Please review CONTRIBUTING.md before submitting changes.
The wheel bundles the H2 Database JDBC driver (MPL 2.0 / EPL 1.0). The example data is generated locally by queryapigate examples load; no third-party datasets are included.
QueryAPIGate is source-available, under the Functional Source License, Version 1.1, MIT Future License (FSL-1.1-MIT) © Anantha Raju C. It is not an OSI-approved open source license.
In plain terms - the LICENSE is the only authoritative text:
Need something the license does not cover, such as offering it as part of a hosted service? Get in touch - commercial licensing may be available. This is a summary, not legal advice.
Anantha Raju C - @anantharajuc - arcswdev@gmail.com
Project link: https://github.com/AnanthaRajuC/QueryAPIGate
mysql postgres clickhouse h2 duckdb mongo flow encryption redis mcp jwt all server docs dev
sql api rest rest-api data-api flask database mysql postgresql clickhouse sqlite duckdb mongodb h2 jdbc parquet s3 mcp ai-agents
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Oct 11, 2026.




