Registry / web-framework / graphene-pydantic

graphene-pydantic

JSON →
library0.6.1pypypi✓ verified 84d ago

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"
INSTALL
IMPORT
SIG · GRAPHENE-PYDANTIC
G
graphene-pydantic
web-frameworkpythonv0.6.1
Install
3.7s avg
Import
717ms
Disk
31MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v0.6.1 · 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.920 runs
installs and imports cleanly · install 0.0s · import 0.748s · 32.4MB
glibc
py 3.103.920 runs
installs and imports cleanly · install 3.7s · import 0.686s · 32MB
31MB installed
● package 31MB
Code
Verified usage

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

PydanticObjectType
from graphene_pydantic import PydanticObjectType
PydanticInputObjectType
from graphene_pydantic import PydanticInputObjectType

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.

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'}]
Debug
Known issues
breakingVersion 0.3.0 dropped support for Python 3.6 and Pydantic versions older than 1.7. Ensure your environment meets these minimum requirements.
fix
Upgrade Python to 3.7+ and Pydantic to 1.7+ before upgrading graphene-pydantic to 0.3.0 or later.
affects: 0.3.0 and later
breakingVersion 0.1.0 removed support for Pydantic 0.x. If migrating from very old Pydantic versions, significant changes may be required.
fix
Upgrade Pydantic to a 1.x version first, addressing any Pydantic-specific breaking changes, then upgrade graphene-pydantic.
affects: 0.1.0 and later
gotchaDue to a GraphQL limitation, Pydantic fields that hold mappings (e.g., dictionaries) cannot be directly exported to Graphene types.
fix
Represent dictionary fields as `JSONString` or define custom scalar types/Graphene `ObjectType`s for complex mapping structures, and provide custom resolvers.
affects: All
gotchaGraphQL Input Object Types do not support unions as fields. Attempting to use a Pydantic `Union` type in an `PydanticInputObjectType` will lead to errors.
fix
Avoid `Union` types in `PydanticInputObjectType` fields. Consider using separate input types for each union member or redesigning the input structure.
affects: All
gotchaWhen 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.
fix
Implement `is_type_of` in Graphene models representing union members. For `Union[Subclass, Baseclass]`, define as `Union[Subclass, Baseclass]`.
affects: All
gotchaThe 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.
fix
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.
affects: All (especially when migrating Pydantic versions)
Errors
Common errors & fixes
Don't know how to handle mappings in Graphene.
Graphene's type system does not directly support dictionary (mapping) types, so Pydantic models containing `dict` or `typing.Dict` fields cannot be automatically converted to Graphene `ObjectType`s by `graphene-pydantic`.
fix
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.
TypeError: Input fields cannot be resolved. The input field type must be a GraphQL input type.
This error often occurs when attempting to use Pydantic models with complex structures (like nested models or models utilizing discriminators) as `PydanticInputObjectType`s for GraphQL mutations, as GraphQL input types have limitations on complexity and type resolution.
fix
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.
ValueError: mutable default <class 'list'> for field field is not allowed: use default_factory
This is a Pydantic validation error that occurs when a mutable object (like a list or dictionary) is used directly as a default value in a Pydantic `BaseModel` field, which can lead to unexpected shared state across instances. `graphene-pydantic` processes these models, exposing this underlying Pydantic issue.
fix
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)`.
PydanticUndefinedAnnotation: name '...' is not defined
This Pydantic error indicates that a type annotation in your Pydantic `BaseModel` could not be resolved, often due to a forward reference (a string literal for a type that is defined later) that hasn't been properly handled or imported, preventing `graphene-pydantic` from correctly introspecting the model.
fix
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.
Upgrade
Version history
0.6.1latest on PyPI · released Feb 1, 2024
Audit
Dependencies
graphenerequiredCore dependency for GraphQL schema definition.
pydanticrequiredCore dependency for data model definition.
Agent activity
6 hits · last 30 days
node
6
Resources
graphene-pydantic — pip install graphene-pydantic · libregistry