Graphene Pydantic Integration

0.6.1 · active · verified Wed Apr 15

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

Install

Imports

Quickstart

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'}]

view raw JSON →