A Pydantic integration for Graphene.
pip install "graphene-pydantic"
Here is a simple Pydantic model:
import pydantic class PersonModel(pydantic.BaseModel): id: uuid.UUID first_name: str last_name: str
To create a GraphQL schema for it you simply have to write the following:
import graphene from graphene_pydantic import PydanticObjectType class Person(PydanticObjectType): class Meta: model = PersonModel # only return specified fields only_fields = ("name",) # exclude specified fields exclude_fields = ("id",) class Query(graphene.ObjectType): people = graphene.List(Person) def resolve_people(self, info): return get_people() # function returning `PersonModel`s schema = graphene.Schema(query=Query)
Then you can simply query the schema:
query = ''' query { people { firstName, lastName } } ''' result = schema.execute(query)
Please see the examples directory for more.
This project is under the Apache License.
This project depends on third-party code which is subject to the licenses set forth in Third Party Licenses.
Please see the Contributing Guide. Note that you must sign the CLA.
Note that even though Pydantic is perfectly happy with fields that hold mappings (e.g. dictionaries), because GraphQL's type system doesn't have them those fields can't be exported to Graphene types. For instance, this will fail with an error Don't know how to handle mappings in Graphene
:
import typing from graphene_pydantic import PydanticObjectType class Pet: pass class Person: name: str pets_by_name: typing.Dict[str, Pet] class GraphQLPerson(PydanticObjectType): class Meta: model = Person
However, note that if you use exclude_fields
or only_fields
to exclude those values, there won't be a problem:
class GraphQLPerson(PydanticObjectType): class Meta: model = Person exclude_fields = ("pets_by_name",)