Graphene Pydantic Integration
A Pydantic integration for Graphene, currently at version 0.6.1. It provides utilities to automatically convert Pydantic `BaseModel`s into Graphene `ObjectType`s and `InputObjectType`s, streamlining GraphQL schema generation. The library sees active development with updates addressing Pydantic and Graphene version compatibility.
Warnings
- breaking Version 0.3.0 dropped support for Python 3.6 and Pydantic versions older than 1.7. Ensure your environment meets these minimum requirements.
- breaking Version 0.1.0 removed support for Pydantic 0.x. If migrating from very old Pydantic versions, significant changes may be required.
- gotcha Due to a GraphQL limitation, Pydantic fields that hold mappings (e.g., dictionaries) cannot be directly exported to Graphene types.
- gotcha GraphQL Input Object Types do not support unions as fields. Attempting to use a Pydantic `Union` type in an `PydanticInputObjectType` will lead to errors.
- gotcha When using `Union` types in `PydanticObjectType`, you must explicitly implement the `is_type_of` class method in your Graphene models. For unions between subclasses, the subclass must be listed first in the type annotation to ensure correct resolution.
- gotcha The library supports Pydantic versions `~1.7` through `~2.x`. However, Pydantic itself introduced significant breaking changes between V1 and V2. While `graphene-pydantic` aims to be compatible, migrating your underlying Pydantic models from V1 to V2 may still require substantial refactoring.
Install
-
pip install "graphene-pydantic"
Imports
- PydanticObjectType
from graphene_pydantic import PydanticObjectType
- PydanticInputObjectType
from graphene_pydantic import PydanticInputObjectType
Quickstart
import uuid
import pydantic
import graphene
from graphene_pydantic import PydanticObjectType
class PersonModel(pydantic.BaseModel):
id: uuid.UUID
first_name: str
last_name: str
class Person(PydanticObjectType):
class Meta:
model = PersonModel
exclude_fields = ("id",)
class Query(graphene.ObjectType):
people = graphene.List(Person)
@staticmethod
def resolve_people(parent, info):
# In a real application, you would fetch data from a database
return [
PersonModel(id=uuid.uuid4(), first_name="Alice", last_name="Smith"),
PersonModel(id=uuid.uuid4(), first_name="Bob", last_name="Johnson")
]
schema = graphene.Schema(query=Query)
query = """
query {
people {
firstName,
lastName
}
}
"""
result = schema.execute(query)
print(result.data['people'])
# Expected output: [{'firstName': 'Alice', 'lastName': 'Smith'}, {'firstName': 'Bob', 'lastName': 'Johnson'}]