概要

GraphQLはFacebookにより開発されたオープンソースの言語。

以降では、GraphQLの考え方と簡単な環境構築を行う。

目次

GraphQLの基礎

クエリとミューテーション

TODO:

Fields

https://graphql.org/learn/queries/#fields

Arguments

https://graphql.org/learn/queries/#arguments

Aliases

https://graphql.org/learn/queries/#aliases

Fragments

https://graphql.org/learn/queries/#fragments

Operation Name

https://graphql.org/learn/queries/#operation-name

Variables

https://graphql.org/learn/queries/#variables

Directives

https://graphql.org/learn/queries/#directives

Mutations

https://graphql.org/learn/queries/#mutations

Inline Fragments

https://graphql.org/learn/queries/#inline-fragments

スキーマとタイプ

TODO:

Type System

Type Language

Object Types and Fields

Arguments

The Query and Mutation Types

Scalar Types

Enumeration Types

Lists and Non-Null

Interfaces

Union Types

Input Types

サーバ側の環境構築

pythonライブラリ graphene を使用してサーバ環境を構築する。

準備

pythonの仮想環境を作って graphene をインストールしておく。
※WebAPIとして提供する為、flask と flask-graphql も同時にインストール。

pip install pipenv
pipenv --python 3.7
pipenv install graphene
pipenv install flask
pipenv install flask-grapphql

動作確認用に仮想環境のシェルを起動しておく

pipenv shell

スキーマ 及び リゾルバ関数の定義

schema.py

import graphene

class User(graphene.ObjectType):  # graphene.ObjectType を継承してスキーマ定義
    """スキーマの定義."""
    id = graphene.ID()
    name = graphene.String()
    age = graphene.Int()


class Query(graphene.ObjectType):
    """リゾルバ関数の定義."""
    user = graphene.Field(User)

    def resolve_user(self, info, id):  #「resolve_変数名」でリゾルバ関数を定義する
        return User(id=1, name="Taro", age=20)

# スキーマを生成
schema = graphene.Schema(query=Query)

スキーマ単体での動作確認

test_schema.py

from sample_schema import schema

if __name__ == "__main__":
    query = """ 
        query something {
          user(id: "1") {
            id
            name
            age
          }
        }
    """
    result = schema.execute(query)
    #result = schema.execute(query, {"id": "1"})
    if result.errors:
        print(result.errors)
    else:
        print(result.data)

動作確認の実行

python test_schema.py
OrderedDict([('user', OrderedDict([('id', '1'), ('name', 'Taro'), ('age', 20)]))])

Webサーバの実装

app.py

from schema import schema
from flask import Flask
from flask_graphql import GraphQLView

app = Flask(__name__)
app.debug = True

app.add_url_rule(
    '/',
    view_func=GraphQLView.as_view(
        'graphql',
        schema=schema,
        graphiql=True  # テスト時などにブラウザから利用できるAPIコンソールをONにしておく
    )   
)

if __name__ == '__main__':
    app.run()

サーバ起動

python app.py

WebAPIとしての動作確認

curl http://127.0.0.1:5000/ --data query='{ user(id: "1") { id, name, age}}'
{"data":{"user":{"id":"1","name":"Taro","age":20}}}

※ graphiql=True で起動している場合は、ブラウザから任意のQueryを発行する為の、コンソール画面も提供される。


トップ   一覧 単語検索 最終更新   ヘルプ   最終更新のRSS