Flask plus GraphQL

We’ll build a Flask server to take GraphQL queries.

Install the dependencies — Flask to take queries, Graphene to process them and Flask-GraphQL to simplify the route:

$ pip install flask graphene flask-graphql

Create a server.py:

from flask import Flask
from graphene import ObjectType, String, Schema
from flask_graphql import GraphQLView

class Query(ObjectType):
    hello = String(description='Hello')
    def resolve_hello(self, args, context, info):
        return 'World'

app = Flask(__name__)
app.add_url_rule('/', view_func=GraphQLView.as_view('graphql',
                 schema=Schema(query=Query)))

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

Start the server:

$ python server.py
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

Client

Test with curl:

$ curl -H 'Content-type: application/graphql' -d '{hello}' http://localhost:5000/
{"data": {"hello": "World"}}%

Python Client

$ pip install gql
import json
from gql import gql, Client
from gql.transport.requests import RequestsHTTPTransport

transport = RequestsHTTPTransport('http://localhost:5000/')
client = Client(transport=transport)
response = client.execute(gql('{hello}'))

print(json.dumps(response))
$ python client.py
{"hello": "world"}