Registry / web-framework / graphene

graphene

JSON →
library3.4.3pypypi✓ verified 24d ago

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.

pip install graphene
INSTALL
IMPORT
SIG · GRAPHENE
G
graphene
web-frameworkpythonv3.4.3
Install
2.1s avg
Import
466ms
Disk
21MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v3.4.3 · 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 0.491s · 22.6MB
glibc
py 3.103.910 runs
installs and imports cleanly · install 2.1s · import 0.440s · 23MB
21MB installed
● package 21MB
Code
Verified usage

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

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
from graphene.relay.node import to_global_id
The import path for `to_global_id` changed in Graphene v3.0.0.

This quickstart defines a simple GraphQL schema with a single 'hello' field that returns 'World'. It demonstrates basic schema definition and execution.

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
Debug
Known issues
breakingIn 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.
fix
Review `InputObjectType` usage and resolvers to correctly differentiate between omitted fields and explicitly `null` fields. Consider using `default_value` in `InputField` if `None` implies a default rather than `null`.
affects: >=3.3.0
breakingGraphene 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.
fix
Ensure your project is running Python 3.x. Update argument names from `type` to `type_` where applicable. Review schema definitions and custom backend integrations as they may require refactoring due to underlying `graphql-core` changes.
affects: >=3.0.0 (from 2.x)
breakingThe 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`.
fix
Update imports from `from graphene.relay.node import to_global_id` to `from graphene.relay import to_global_id`.
affects: >=3.0.0 (from 2.x)
gotchaGraphene 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.
fix
If you are using Python versions less than 3.11 and the `DateTime` scalar, ensure you upgrade Graphene to v3.4.1 or later to avoid parsing errors.
affects: 3.4.0 (for Python < 3.11 users)
gotchaWhen 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.
fix
Ensure that any custom `Connection` classes you define for your SQLAlchemy models have unique names that do not clash with those `graphene-sqlalchemy` might generate automatically.
affects: All versions of `graphene-sqlalchemy`
Errors
Common errors & fixes
AttributeError: module 'graphene' has no attribute 'string'
Graphene's scalar types like String, Int, Boolean, etc., are defined with an uppercase first letter (e.g., `graphene.String`), but developers often mistakenly use lowercase, leading to an AttributeError due to Python's case sensitivity.
fix
Ensure that Graphene's scalar types are referenced with the correct capitalization (e.g., `graphene.String` instead of `graphene.string`).

```python
import graphene

class MyType(graphene.ObjectType):
    my_field = graphene.String()
```
TypeError: __init__() missing 1 required positional argument: 'get_response'
This error commonly occurs in `graphene-django` setups, particularly when configuring `graphql_jwt` middleware. It often indicates an incorrect or missing `MIDDLEWARES` setting in Django's `settings.py`, or improper placement/definition of the JWT middleware.
fix
Ensure that `graphql_jwt.middleware.JSONWebTokenMiddleware` is correctly added to both Django's `MIDDLEWARE` list and Graphene's `GRAPHENE` setting under `'MIDDLEWARES'` (note the plural 'S').

```python
# settings.py
MIDDLEWARE = [
    # ... other Django middleware
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'graphql_jwt.middleware.JSONWebTokenMiddleware',
    # ...
]

GRAPHENE = {
    'SCHEMA': 'your_project.schema.schema',
    'MIDDLEWARES': [
        'graphql_jwt.middleware.JSONWebTokenMiddleware',
    ],
}
```
AttributeError: 'NoneType' object has no attribute 'get'
This general Python error, when seen in Graphene, often means a resolver function returned `None` when an object was expected, or an attempt was made to access an attribute (like `.get()`) on `info.context` or another object that was unexpectedly `None`.
fix
Debug the resolver chain to identify where `None` is being returned instead of an object. Ensure that parent resolvers return valid objects (or dictionaries) and that `info.context` is properly populated if you are relying on it.

```python
# Example of a resolver returning None incorrectly
# def resolve_my_field(root, info):
#     user = User.objects.filter(id=root.user_id).first() # if user is not found, it's None
#     return user.name # This would raise the error if user is None

# Corrected resolver
def resolve_my_field(root, info):
    user = User.objects.filter(id=root.user_id).first()
    if user:
        return user.name
    return None # Or raise a specific error/return a default value
```
ImportError: cannot import name 'ResolveInfo' from 'graphql'
This error typically indicates a version incompatibility between the `graphene` library and its underlying `graphql-core` dependency. The name or location of the `ResolveInfo` class might have changed in a newer `graphql-core` version than `graphene` expects.
fix
Upgrade Graphene and its dependencies to compatible versions. If you are on an older Graphene version, consider upgrading to Graphene 3.x, which usually has updated dependency ranges. Alternatively, you might need to pin `graphql-core` to a specific version known to be compatible with your Graphene installation.

```bash
pip install --upgrade graphene graphql-core
# If still problematic, try pinning graphql-core (e.g., for older Graphene versions)
# pip install graphene==2.1.8 graphql-core==2.3.2
```
Graphene Mutation error, fields must be a mapping (dict / OrderedDict)
This error often occurs in `graphene-django` when a developer mistakenly imports `ObjectType` from `graphene` instead of `DjangoObjectType` from `graphene_django.types` when defining GraphQL types that should be linked to Django models. Mutations expect a specific structure which `DjangoObjectType` provides for model-backed types.
fix
When defining GraphQL types that represent Django models, ensure you import `DjangoObjectType` from `graphene_django.types` and inherit from it, especially in mutations where input fields are derived from the model.

```python
# Wrong:
# from graphene import ObjectType
# class MyModelType(ObjectType):
#     class Meta:
#         model = MyModel

# Correct:
from graphene_django.types import DjangoObjectType

class MyModelType(DjangoObjectType):
    class Meta:
        model = MyModel
```
Upgrade
Version history
3.4.3latest on PyPI · released Nov 9, 2024
Audit
Dependencies
graphql-corerequiredCore GraphQL implementation, Graphene v3 requires graphql-core v3 or higher.
python-dateutiloptionalRequired for DateTime scalar parsing on Python versions prior to 3.11 (since Graphene v3.4.1).
graphene-djangooptionalOfficial integration for Django framework.
graphene-sqlalchemyoptionalOfficial integration for SQLAlchemy ORM.
Agent activity
19 hits · last 30 days
node
18
Resources
graphene — pip install graphene · libregistry