Last active
March 4, 2019 05:00
-
-
Save a-y-khan/69189c26df2dcbc8a252b02af897977d to your computer and use it in GitHub Desktop.
Graphene Hello World
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# https://gist.github.com/a-y-khan/69189c26df2dcbc8a252b02af897977d | |
# Super-simple example from Graphene tutorial | |
import graphene | |
from gql import gql, Client | |
class Query(graphene.ObjectType): | |
hello = graphene.String(argument=graphene.String(default_value='world')) | |
# this is where the magic happens! | |
# pattern is always resolve_<field> | |
def resolve_hello(self, info, argument): | |
# info: | |
# ResolveInfo class: https://github.com/graphql-python/graphql-core | |
return 'hello ' + argument | |
schema = graphene.Schema(query=Query) | |
if '__main__' == __name__: | |
# GraphQL's serialization format is JSON! | |
query = """ | |
{ | |
hello | |
} | |
""" | |
query_with_argument = """ | |
{ | |
hello(argument: "Pythonistas!") | |
} | |
""" | |
# result is OrderedDict | |
result = schema.execute(query) | |
print(result.data['hello']) | |
result = schema.execute(query_with_argument) | |
print(result.data['hello']) | |
# using the Graphene GraphQL Python client | |
# returns results directly (as OrderedDict, which is the same as above...) | |
client = Client(schema=schema) | |
gql_query = gql(query) | |
gql_query_with_argument = gql(query_with_argument) | |
result = client.execute(gql_query) | |
print(result['hello']) | |
result = client.execute(gql_query_with_argument) | |
print(result['hello']) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment