Registry / web-framework / graphene-sqlalchemy

graphene-sqlalchemy

JSON →
library2.3.0pypypi✓ verified 21d ago

Graphene SQLAlchemy integration allows developers to quickly and easily create a GraphQL API that seamlessly interacts with a SQLAlchemy-managed database. It is fully compatible with SQLAlchemy 1.4 and 2.0. The current stable version is 2.3.0, but version 3.0 is in release candidate stage with significant updates, and the project has an active development cadence.

pip install "graphene-sqlalchemy"
INSTALL
IMPORT
SIG · GRAPHENE-SQLALCHEM
G
graphene-sqlalchemy
web-frameworkpythonv2.3.0
Install
5.6s avg
Import
992ms
Disk
48MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v3.0.0rc2 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.910 runs
installs and imports cleanly · install 0.0s · import 1.036s · 46.7MB
glibc
py 3.103.910 runs
installs and imports cleanly · install 5.6s · import 0.948s · 49MB
48MB installed
● package 48MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

SQLAlchemyObjectType
from graphene_sqlalchemy import SQLAlchemyObjectType
SQLAlchemyConnectionField
from graphene_sqlalchemy import SQLAlchemyConnectionField

This quickstart demonstrates how to define a SQLAlchemy model, create a `SQLAlchemyObjectType` from it, and then build a Graphene schema that can query the data. It's crucial to provide an active SQLAlchemy session to the GraphQL execution context for resolvers to function correctly.

import graphene from graphene_sqlalchemy import SQLAlchemyObjectType from sqlalchemy import create_engine, Column, Integer, String from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base # 1. Define SQLAlchemy Model Base = declarative_base() class UserModel(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True) name = Column(String) email = Column(String, unique=True) def __repr__(self): return f"<User(name='{self.name}', email='{self.email}')>" # 2. Configure Database Session engine = create_engine('sqlite:///:memory:') Base.metadata.create_all(engine) Session = sessionmaker(bind=engine) session = Session() # Add some initial data user1 = UserModel(name='Alice', email='alice@example.com') user2 = UserModel(name='Bob', email='bob@example.com') session.add_all([user1, user2]) session.commit() # 3. Create Graphene Object Type from SQLAlchemy Model class User(SQLAlchemyObjectType): class Meta: model = UserModel interfaces = (graphene.relay.Node,) # Optionally expose specific fields or exclude some # only_fields = ("name", "email") # exclude_fields = ("id",) # 4. Define Query Type class Query(graphene.ObjectType): node = graphene.relay.Node.Field() all_users = graphene.List(User) user_by_name = graphene.Field(User, name=graphene.String(required=True)) def resolve_all_users(self, info): # Graphene-SQLAlchemy provides get_query to construct a query # for the model associated with the SQLAlchemyObjectType query = User.get_query(info) return query.all() def resolve_user_by_name(self, info, name): query = User.get_query(info) return query.filter(UserModel.name == name).first() # 5. Create Schema schema = graphene.Schema(query=Query) # 6. Execute a Query query = ''' query { allUsers { name email } userByName(name: "Alice") { name email } } ''' result = schema.execute(query, context_value={'session': session}) print(result.data) # Expected output might look like: # {'allUsers': [{'name': 'Alice', 'email': 'alice@example.com'}, {'name': 'Bob', 'email': 'bob@example.com'}], 'userByName': {'name': 'Alice', 'email': 'alice@example.com'}}
Debug
Known issues
breakingVersion 3.x of `graphene-sqlalchemy` drops support for Python 3.7 and 3.8, requiring Python 3.9 or newer. Users upgrading to v3.x must ensure their Python environment meets this requirement.
fix
Upgrade Python to 3.9+ before upgrading `graphene-sqlalchemy` to v3.x.
affects: 3.x.x
breakingVersion 3.x introduces full compatibility with SQLAlchemy 2.0 and replaces the internal `promises.dataloader` with `aiodalaloader`. This makes batched queries asyncio-dependent, requiring applications to adapt to the new asynchronous DataLoader implementation.
fix
Review and update DataLoader implementations to use `aiodalaloader` and ensure asynchronous handling for batched queries. Consult the v3.x upgrade guide for detailed changes.
affects: 3.x.x
breakingIn version 3.x, `graphene-sqlalchemy` introduces automatic type detection for SQLAlchemy `hybrid_property` methods based on Python type hints. Previously, these were often implicitly converted to `String` in the GraphQL schema unless explicitly overridden. This change may lead to unexpected GraphQL schema type changes for `hybrid_property` fields.
fix
Explicitly define the Graphene type for `hybrid_property` fields in your `SQLAlchemyObjectType` `Meta` class or by adding type hints to the `hybrid_property` method if relying on automatic detection.
affects: 3.x.x
breakingVersion 3.x overhauls the filtering syntax, incorporating new filters directly and removing the need for external filtering plugins. This means existing custom filtering logic or reliance on `graphene-sqlalchemy-filter` will likely break.
fix
Refactor custom filters to align with the new built-in filtering capabilities in `graphene-sqlalchemy` v3.x.
affects: 3.x.x
gotchaA SQLAlchemy session is critical for `graphene-sqlalchemy` to resolve models and execute queries. Forgetting to provide a session to the GraphQL execution context will result in errors.
fix
Always pass an active SQLAlchemy session via the `context_value` argument when executing a Graphene schema (e.g., `schema.execute(query, context_value={'session': db_session})`). Alternatively, for declarative models, `Base.query = db_session.query_property()` can set a default query property.
affects: All
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'graphene-sqlalchemy'
The `graphene-sqlalchemy` library is not installed in your Python environment or the environment where your application is running.
fix
Install the library using pip: `pip install "graphene-sqlalchemy>=2.0"` (or `pip install "graphene-sqlalchemy"` for the latest stable version).
AssertionError: You need to pass a valid SQLAlchemy Model in YourObjectType.Meta, received "<class 'sqlalchemy.ext.automap.YourModel'>"
The `model` attribute within the `Meta` class of your `SQLAlchemyObjectType` is not referencing a properly mapped SQLAlchemy declarative base model. This can happen with issues like using `automap_base()` without ensuring the classes are correctly prepared or passing an unmapped class.
fix
Ensure your SQLAlchemy model is properly defined using `declarative_base()` and that it has been mapped before being passed to `SQLAlchemyObjectType.Meta`. For `automap_base`, ensure `prepare()` has been called on the base. Example: `class YourModelType(SQLAlchemyObjectType): class Meta: model = YourModel` where `YourModel` is a class inheriting from `Base` (e.g., `Base = declarative_base(); class YourModel(Base): ...`).
A query in the model Base or a session in the schema is required for querying
Graphene-SQLAlchemy requires a SQLAlchemy session to be provided (typically in the GraphQL context) or a `query` attribute on the `SQLAlchemyObjectType`'s `Meta` class to resolve data.
fix
Provide a SQLAlchemy session in the `context_value` when executing your schema, or define a `get_query` method or `query` attribute on your `SQLAlchemyObjectType`'s `Meta` class if you're managing queries differently. Example with context: `schema.execute(query, context_value={'session': db_session})`.
AttributeError: type object 'YourModelType' has no attribute 'connection'
This error often occurs when attempting to use Relay connections with `SQLAlchemyObjectType` but the `SQLAlchemyObjectType` itself hasn't been configured to implement the `relay.Node` interface, which is necessary for `SQLAlchemyConnectionField` to create connection types.
fix
Ensure your `SQLAlchemyObjectType` explicitly inherits from `graphene.relay.Node` in its `Meta.interfaces` tuple. Example: `class YourModelType(SQLAlchemyObjectType): class Meta: model = YourModel; interfaces = (relay.Node,)`.
Upgrade
Version history
2.3.0latest on PyPI · released Jun 4, 2020
Audit
Dependencies
graphenerequiredCore GraphQL library; graphene-sqlalchemy v3.x specifically benefits from graphene>=3.1.1.
SQLAlchemyrequiredORM for database interaction; graphene-sqlalchemy v3.x supports SQLAlchemy 1.4 and 2.0.
aiodalaloaderoptionalUsed for batching in graphene-sqlalchemy v3.x, replacing promises.dataloader for asyncio-dependent queries.
Agent activity
7 hits · last 30 days
node
6
Resources
graphene-sqlalchemy — pip install graphene-sqlalchemy · libregistry