Graphene
Graphene is an opinionated Python library for building GraphQL APIs easily. It provides a simple yet extendable API, with built-in support for Relay and integrations for popular web frameworks like Django and SQLAlchemy. The current stable version is 3.4.3, with active development and frequent releases.
Warnings
- breaking In Graphene v3.3.0 and later, if an optional field in an `InputObjectType` is omitted in a GraphQL query, it is now passed as `None` to the Python input. This makes it indistinguishable from a field explicitly passed with `null`, requiring changes to how `None` values are interpreted in your resolvers.
- breaking Graphene v3.0.0 involved a significant upgrade to `graphql-core` v3, dropping support for Python 2. Major changes include modifications to schema types, removal of the 'backends' concept, and renaming the `type` argument to `type_` in various Graphene constructs (e.g., `Field`, `Argument`) to avoid clashes with the Python built-in `type` function.
- breaking The import path for the `to_global_id` utility function, frequently used with Relay, changed in Graphene v3.0.0. Code importing it from `graphene.relay.node.to_global_id` will now raise an `ImportError`.
- gotcha Graphene v3.4.0 removed the `aniso8601` dependency, which caused a regression in `DateTime` scalar parsing for Python versions prior to 3.11. This issue was resolved in v3.4.1 by introducing `python-dateutil` for `DateTime` parsing on Python < 3.11.
- gotcha When using `graphene-sqlalchemy`, automatically generated connection classes (e.g., `UserConnection` for a `User` model) can conflict with custom `Connection` classes you define if they share the same name. This can lead to unexpected errors during schema generation or execution.
Install
-
pip install graphene -
pip install 'graphene>=3.1'
Imports
- ObjectType
from graphene import ObjectType
- String
from graphene import String
- Schema
from graphene import Schema
- Field
from graphene import Field
- to_global_id
from graphene.relay import to_global_id
Quickstart
import graphene
class Query(graphene.ObjectType):
hello = graphene.String(description='A typical hello world')
def resolve_hello(self, info):
return 'World'
schema = graphene.Schema(query=Query)
# Example usage:
query = '''
query SayHello {
hello
}
'''
result = schema.execute(query)
print(result.data['hello'])
# Expected output: World