[hypequery](https://hypequery.com/) › ClickHouse with FastAPI: Secure Analytics APIs in Python | hypequery
Index for agents: https://hypequery.com/llms.txt
Canonical page: https://hypequery.com/clickhouse-fastapi

> Serve ClickHouse analytics from FastAPI with authenticated, tenant-scoped endpoints, strict request validation, rate limiting, and a production profile.

[Open sourceApache 2.0](https://github.com/hypequery/hypequery)

ClickHouse FastAPI

# Serve ClickHouse analytics from FastAPI without hand-writing every endpoint

Most FastAPI analytics endpoints are the same code repeated: parse filters, build SQL, add the tenant, check permissions, shape errors. hypequery serves your ClickHouse datasets as authenticated, tenant-scoped endpoints, so the route stops being where the analytics logic lives.

[Read the FastAPI guide ](https://hypequery.com/docs/python/fastapi)[ClickHouse with Python](https://hypequery.com/clickhouse-python)

Framework

Mounted in FastAPI

Auth

Bearer tokens or API keys

Default

Authenticated, docs closed

## Every endpoint rebuilds the same plumbing

Filter parsing, SQL building, pagination, and error shapes get reimplemented per route, and each one handles the edge cases slightly differently.

## Tenant scoping lives in handler code

If each handler adds its own tenant filter, one missed handler exposes another customer’s data. The safe default should not depend on every developer remembering it.

## Request bodies become an attack surface

Flexible analytics endpoints invite callers to send SQL fragments, extra fields, or a different tenant id. Validation has to be strict, and it is easy to get wrong.

Serve

## Register a dataset as an authenticated endpoint, then mount it

Every route on the API requires authentication unless you mark it public, and authentication runs before the body is read. The tenant always comes from the authenticated principal.

- Bearer token or API key credentials, verified by your own authenticator
- Per-endpoint roles, scopes, and tenant requirements
- Strict JSON bodies: unknown fields, coercion, and tenant or SQL injection attempts are refused
- Pagination, result metadata, and an authenticated discovery catalog
- Rate limiting, allowed hosts, CORS, trusted proxies, and request ids

API

### A tenant-scoped dataset endpoint

serve.py

```
from fastapi import FastAPI
from hypequery.serve import (
    Credential, EndpointPolicy, HttpSecurity, Principal,
    add_dataset_endpoint, create_api, to_asgi_app,
)

async def authenticate(credential: Credential) -> Principal | None:
    claims = await verify_jwt(credential.value)  # your token verification
    if claims is None:
        return None
    return Principal(
        subject=claims["sub"],
        scopes=frozenset(claims.get("scope", "").split()),
        tenant_id=claims.get("org_id"),
    )

api = create_api(
    auth=authenticate,
    security=HttpSecurity(allowed_hosts=("analytics.example.com",)),
)
add_dataset_endpoint(
    api,
    "/datasets/orders/query",
    dataset=orders,
    client=analytics,
    policy=EndpointPolicy(
        required_scopes=frozenset({"analytics:read"}), tenant="required"
    ),
)

app = FastAPI()  # your existing app and routes
app.mount("/analytics", to_asgi_app(api))
```

`orders` and `analytics` are the dataset and client from your Python model.

Call it

## One request shape for every dataset

Callers post dimensions, measures, filters, ordering, a time grain, and pagination. Errors use one envelope with stable types, so clients handle them the same way everywhere.

The request and response shapes match the TypeScript Serve runtime, and shared HTTP fixtures run against both implementations in CI. HTTP clients written against one work against the other.

For a standalone service, the production profile runs one hardened Uvicorn worker with concurrency, timeout, row, and byte limits, and rejects debug settings at startup.

Request

### Query the endpoint over HTTP

call-it.py

```
curl -X POST https://analytics.example.com/analytics/datasets/orders/query \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"dimensions": ["country"], "measures": ["revenue"], "limit": 10}'

# {"data": [{"country": "NZ", "revenue": "1200.50"}]}

# Without a token:
# 401 {"error": {"type": "UNAUTHORIZED", "message": "Access denied", ...}}
```

Measure values are strings on the wire, matching TypeScript.

Where teams usually get stuck

## Questions teams ask

### How do I query ClickHouse from FastAPI?

Call a ClickHouse client such as clickhouse-connect from your route handlers, or define datasets once and mount hypequery's API with `app.mount("/analytics", to_asgi_app(api))`. The mounted endpoints authenticate each request and scope it to the caller's tenant.

### Who this is for

Teams exposing ClickHouse analytics from a Python backend, especially to customers in a multi-tenant product.

### Does it work with my existing FastAPI app?

The API is a plain ASGI app, so it mounts under a prefix in your existing FastAPI app. Your own routes stay exactly as they are.

### Security defaults

Docs and OpenAPI are closed unless you enable them for development, and authenticated responses are never cached.

### Where to go next

Start with the Python datasets docs if you have not modelled a table yet, then come back to serving. To call these endpoints from React or an AI agent, add a client profile and generate typed hooks.

Examples

## Runnable examples

Every example runs against the same seeded ClickHouse dataset. Scaffold one with `npx @hypequery/cli create <slug> -y`, or browse the [full list](https://hypequery.com/examples).

[Example · Python](https://hypequery.com/examples/fastapi-analytics-api)

### [A FastAPI analytics API on ClickHouse with tenant-scoped datasets](https://hypequery.com/examples/fastapi-analytics-api)

[Serve governed ClickHouse analytics from FastAPI: datasets defined once in Python, query endpoints mounted beside your routes, tenant fixed by the token.](https://hypequery.com/examples/fastapi-analytics-api)

[PythonFastAPIClickHouseAnalytics APIMulti-tenantSaaS analytics](https://hypequery.com/examples/fastapi-analytics-api)

[Open example](https://hypequery.com/examples/fastapi-analytics-api)

Further reading

## Go deeper where it actually helps

### [Python Serve docs](https://hypequery.com/docs/python/fastapi)

[Getting started, dataset endpoints, authentication, and multi-tenancy.](https://hypequery.com/docs/python/fastapi)

[Open guide](https://hypequery.com/docs/python/fastapi)

### [Production profile](https://hypequery.com/docs/python/production)

[Run the service with validated process, timeout, and result limits.](https://hypequery.com/docs/python/production)

[Open guide](https://hypequery.com/docs/python/production)

### [ClickHouse with Python](https://hypequery.com/clickhouse-python)

[Model ClickHouse tables as datasets and query them by name.](https://hypequery.com/clickhouse-python)

[Open guide](https://hypequery.com/clickhouse-python)

### [React and MCP clients](https://hypequery.com/docs/python/client-endpoints)

[Type-safe React hooks and agent tools over the same endpoints.](https://hypequery.com/docs/python/client-endpoints)

[Open guide](https://hypequery.com/docs/python/client-endpoints)

### [ClickHouse REST API](https://hypequery.com/clickhouse-api)

[The same served API pattern in TypeScript.](https://hypequery.com/clickhouse-api)

[Open guide](https://hypequery.com/clickhouse-api)

Related pillars

[ClickHouse Flask](https://hypequery.com/clickhouse-flask)[ClickHouse Django](https://hypequery.com/clickhouse-django)[ClickHouse Python](https://hypequery.com/clickhouse-python)[Python semantic layer](https://hypequery.com/python-semantic-layer)[Python multi-tenancy](https://hypequery.com/clickhouse-python-multi-tenant)[FastAPI + React](https://hypequery.com/fastapi-react-analytics)[MCP for Python backends](https://hypequery.com/clickhouse-python-mcp)[ClickHouse with Pydantic AI](https://hypequery.com/clickhouse-pydantic)

Next step

## Serve one dataset behind your existing auth

Wire your token verification into the authenticator, register one dataset endpoint, and point a dashboard or customer integration at it.

Open source, and it runs in your own backend. Want it hosted?

[Read the FastAPI guide ](https://hypequery.com/docs/python/fastapi)[Authentication docs](https://hypequery.com/docs/python/authentication)
