Skip to main content

db-graphql-gateway

PyPI version Documentation License: MIT CI Integration Conformance Docs

📚 Full Documentation: forgedlohar.github.io/db-graphql-gateway
🐙 GitHub Repository: forgedlohar/db-graphql-gateway

A production-grade, reusable Python package that automatically generates a secure, optimized GraphQL API directly from your database connection.

It acts as a bridge between your database and GraphQL, translating GraphQL queries into efficient, parameterized SQL without requiring you to manually write resolvers, define schemas, or worry about the typical pitfalls of database-to-API integrations.

GraphiQL IDE showing a nested query against db-graphql-gateway with 3 DB queries total

Live GraphiQL explorer at localhost:8000/graphql — zero resolver code written. 3 queries total for a depth-3 nested query across 5 users.

📦 Installation

Available on PyPI. Install via pip or uv:

pip install "db-graphql-gateway[fastapi]"

✨ Features

  • No ORM Required: The database itself is the source of truth. You don't need to define models in SQLAlchemy, SQLModel, Django, or Prisma just to get a GraphQL API.
  • Security First: Authentication and Authorization are treated as separate concerns. Authorization is implemented as SQL predicates, meaning data filtering happens deep at the database engine level.
  • N+1 Prevention Guarantee: A sophisticated, request-scoped DataLoader pattern is wired up automatically. Combined with integrated authorization predicates, it guarantees O(1) database queries per relationship depth.
  • Zero Raw SQL Exposure: Clients never provide SQL fragments. All filters, sorting rules, and pagination constraints are strictly typed GraphQL arguments, protecting you from SQL injection.
  • AST Security Limits: Configured max_depth and max_aliases protections via QueryDepthLimiter and MaxAliasesLimiter to harden the gateway against expansive query attacks.

⚡ Quickstart Example

Here is a complete example of connecting to your database, building the GraphQL schema dynamically, and mounting it in FastAPI.

import asyncio
import uvicorn
from fastapi import FastAPI
from db_graphql_gateway.database.adapters.postgres.adapter import PostgresAdapter
from db_graphql_gateway.schema.config import GatewayConfig
from db_graphql_gateway.graphql.builder import GraphQLSchemaBuilder
from db_graphql_gateway.auth.authorization import AuthorizationEngine
from db_graphql_gateway.auth.providers import JWTAuthenticationProvider
import strawberry
from strawberry.fastapi import GraphQLRouter

# 1. Initialize the Database Adapter
# Other adapters (MySQLAdapter, SQLiteAdapter) are also available.
db_adapter = PostgresAdapter(dsn="postgresql://user:password@localhost:5432/my_db")

# 2. Configure Security & Authorization
auth_engine = AuthorizationEngine()
auth_provider = JWTAuthenticationProvider(secret_key="super-secret")
config = GatewayConfig()

async def lifespan(app: FastAPI):
    # Connect to the database on startup
    await db_adapter.connect()
    yield
    # Cleanup on shutdown
    await db_adapter.close()

app = FastAPI(lifespan=lifespan)

@app.on_event("startup")
async def setup_graphql():
    # 3. Build the GraphQL Schema dynamically from the database
    schema_builder = GraphQLSchemaBuilder(
        db_adapter=db_adapter, 
        config=config, 
        auth_engine=auth_engine
    )
    schema = await schema_builder.build_schema()
    
    # 4. Mount the Strawberry Router onto FastAPI
    graphql_app = GraphQLRouter(
        schema, 
        context_getter=lambda req: {"request": req, "auth_provider": auth_provider}
    )
    app.include_router(graphql_app, prefix="/graphql")

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)

Example GraphQL Query

Once running, you can hit http://localhost:8000/graphql and execute complex relational queries:

query {
  users(first: 10, filter: { isActive: { eq: true } }) {
    edges {
      node {
        id
        username
        posts {
          title
        }
      }
    }
  }
}

🏗 Architecture Highlights

The system is decoupled into three primary layers, giving you total control before the schema is ever exposed to the client.

  1. Introspection: Connects to PostgreSQL, MySQL, or SQLite and introspects tables, columns, primary keys, foreign keys, and views.
  2. Intermediate Representation (IR): Converts the raw DB schema into a database-agnostic IR. This is where your YAML configurations override names or hide sensitive fields.
  3. GraphQL Generation: The IR dynamically builds a fully-typed Strawberry GraphQL schema.
  4. Query Execution: ASTs are parsed, authorization policies are merged, and highly optimized SQL (EXISTS, JOIN, IN) is generated to fulfill the request.

🤝 Contributing

We welcome contributions! Whether it's fixing a typo, adding a new database adapter, or improving performance, your help is appreciated.

Please see our Contributing Guide for details on how to get started, run tests, and submit pull requests.

Metadata

Release files for db-graphql-gateway 0.3.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for db-graphql-gateway 0.3.1
File Size Uploaded
db_graphql_gateway-0.3.1.tar.gz 687.9 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for db-graphql-gateway 0.3.1
File Interpreter ABI Platform
db_graphql_gateway-0.3.1-py3-none-any.whl Python 3 none any Details

Total release size: 752.0 kB

Release files / db_graphql_gateway-0.3.1.tar.gz

Download URL db_graphql_gateway-0.3.1.tar.gz
Size 687.9 kB
Tags Source
SHA-256 checksum
How to use checksums
3a4282bfd7863a3d4770726f7b2872808e9ea55a203d82e9bacee647a8579e5e
BLAKE2b-256 checksum
How to use checksums
b54c0bac8b931c0eb78d5b8b4395166c9345589f026070690478c3b0c99f458b
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

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 Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 27, 2026.

Transparency log

Release files / db_graphql_gateway-0.3.1-py3-none-any.whl

Download URL db_graphql_gateway-0.3.1-py3-none-any.whl
Size 64.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
1d353d6b8c0bbde8866ea8ed9b0615ef5029be413609a22a315673f5f4564379
BLAKE2b-256 checksum
How to use checksums
c48683f225656ac360cc4aaa1432ab222e474bbbd301e8228c5fbd17d6cc5410
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

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 Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 27, 2026.

Transparency log

Release history Release notifications | RSS feed

0.3.2

2 release files

This release

0.3.1 This release

2 release files

0.3.0

2 release files

0.2.0

2 release files

0.1.2

2 release files

0.1.1

1 release file

0.1.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page