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
muslpy 3.10–3.910 runs
installs and imports cleanly · install 0.0s · import 1.036s · 46.7MB
glibcpy 3.10–3.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'}}
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.
fixInstall 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.
fixEnsure 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.
fixProvide 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.
fixEnsure 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.