How to use GraphQL in Python with Flask?

Flask 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"

view_func = GraphQLView.as_view("graphql", schema=Schema(query=Query))

app = Flask(__name__)
app.add_url_rule("/", view_func=view_func)

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 -g 'http://localhost:5000/?query={hello}'
{"data":{"hello":"World"}}

Python Client

pip install gql requests
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}"))
>>> json.dumps(response)
{"hello": "World"}