• home
  • about
  • 全ての投稿
  • ソフトウェア・ハードウェアの設定のまとめ
  • 分析関連のまとめ
  • ヘルスケア関連のまとめ
  • 生涯学習関連のまとめ

graphen

date: 2022-06-29 excerpt: graphenの使い方

tag: graphqlpythongraphene


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)

Google Colab

  • graphene-example

参考

  • /docs.graphene-python.org/


graphqlpythongraphene Share Tweet