graphenの使い方
概要
- pythonでGraphQLを実現するツール
- Facebookが提唱したRESTに替わるAPIのIF
- GraphQL自体はそんなに流行っていない
インストール
$ python3 -m pip install graphene
具体例
スキーマの定義
from graphene import ObjectType, String, Schema
class Query(ObjectType):
# this defines a Field `hello` in our Schema with a single Argument `name`
hello = String(name=String(default_value="stranger"))
goodbye = String()
# our Resolver method takes the GraphQL context (root, info) as well as
# Argument (name) for the Field and returns data for the query Response
def resolve_hello(root, info, name):
return f'Hello {name}!'
def resolve_goodbye(root, info):
return 'See ya!'
schema = Schema(query=Query)
スキーマに対してクエリを実行
# example 1
query_string = '{ hello }'
result = schema.execute(query_string)
print(result.data['hello']) # "Hello stranger!"
# example 2
query_with_argument = '{ hello(name: "GraphQL") }'
result = schema.execute(query_with_argument)
print(result.data['hello']) # "Hello GraphQL!"
# example 3
result = schema.execute("""
{
goodbye
}
""")
print(result) # ExecutionResult(data={'goodbye': 'See ya!'}, errors=None)
# example 4
result = schema.execute("""
{
hello(name: "test")
goodbye
}
""")
print(result) # ExecutionResult(data={'hello': 'Hello test!', 'goodbye': 'See ya!'}, errors=None)