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.
pip install "graphene-pydantic"Verified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to define a Pydantic model and automatically convert it into a Graphene `ObjectType` using `PydanticObjectType`. It then sets up a basic GraphQL schema and executes a sample query.
Upgrade Python to 3.7+ and Pydantic to 1.7+ before upgrading graphene-pydantic to 0.3.0 or later.
Upgrade Pydantic to a 1.x version first, addressing any Pydantic-specific breaking changes, then upgrade graphene-pydantic.
Represent dictionary fields as `JSONString` or define custom scalar types/Graphene `ObjectType`s for complex mapping structures, and provide custom resolvers.
Avoid `Union` types in `PydanticInputObjectType` fields. Consider using separate input types for each union member or redesigning the input structure.
Implement `is_type_of` in Graphene models representing union members. For `Union[Subclass, Baseclass]`, define as `Union[Subclass, Baseclass]`.
Refer to Pydantic's official migration guide for V1 to V2 changes. Use Pydantic's `bump-pydantic` tool for automated code transformation where possible. Thoroughly test your Graphene schema after Pydantic model updates.
Exclude the dictionary field using `exclude_fields` in the `PydanticObjectType.Meta` class, or convert the dictionary to a supported Graphene type manually via a custom `graphene.Field` and a `resolve_` method.
Ensure that nested Pydantic models intended for input are also defined as `PydanticInputObjectType`s and that GraphQL type system constraints (e.g., no unions in input types) are respected. For circular references or complex nested inputs, ensure all types are properly registered and potentially use `resolve_placeholders()` if forward references are involved.
Use `default_factory` for mutable default values in your Pydantic `BaseModel`s. For example, instead of `field: list[str] = []`, use `field: list[str] = Field(default_factory=list)`.
Ensure all type annotations are correctly imported and accessible. For forward references, make sure the referenced type is defined in the module, or provide a `_types_namespace` if the model is defined within a function or a local scope. If using circular references with `graphene-pydantic`, call `resolve_placeholders()` on your `PydanticObjectType`s after all models are defined.