Flask-GraphQL
Flask-GraphQL adds GraphQL support to your Flask application, providing an easy way to integrate a GraphQL API endpoint and an optional GraphiQL IDE. The library is currently at version 2.0.1 and has a stable, though not rapid, release cadence, focusing on compatibility with Flask and core GraphQL Python libraries.
Warnings
- breaking Flask-GraphQL 2.x is incompatible with `graphql-core` v3.x and `graphene` v3.x due to strict dependency pinning (`graphql-core <3,>=2.1`). Attempting to install or upgrade to `graphql-core` v3.x or `graphene` v3.x will result in dependency conflicts.
- gotcha When using Graphene v3 (if you manage to override `graphql-core` incompatibility or are on a future `flask-graphql` version), passing the Graphene `Schema` object directly to `GraphQLView.as_view`'s `schema` parameter is incorrect. You must use the `graphql_schema` attribute of the Graphene `Schema` object.
- gotcha Enabling batch GraphQL queries requires an additional URL rule definition with `batch=True`. Without this, clients expecting batch query functionality will encounter errors.
- gotcha Flask-GraphQL supports Flask 2.x, but be aware that Flask 2.0 introduced several breaking changes itself, including dropping support for Python 2 and 3.5. Ensure your Python environment and other Flask extensions are compatible with Flask 2.x before upgrading.
Install
-
pip install flask-graphql
Imports
- GraphQLView
from flask_graphql import GraphQLView
Quickstart
import os
from flask import Flask
from flask_graphql import GraphQLView
import graphene
class Query(graphene.ObjectType):
hello = graphene.String(description='A typical hello world')
def resolve_hello(self, info):
# In a real app, 'info' can contain request context, e.g., for auth
# For this example, we'll just return a string.
return 'Hello, World!'
schema = graphene.Schema(query=Query)
app = Flask(__name__)
app.add_url_rule(
'/graphql',
view_func=GraphQLView.as_view(
'graphql',
schema=schema,
graphiql=True # Enable the GraphiQL IDE for testing
)
)
# Optional: for adding batch query support (used in Apollo-Client)
app.add_url_rule(
'/graphql/batch',
view_func=GraphQLView.as_view(
'graphql_batch',
schema=schema,
batch=True
)
)
if __name__ == '__main__':
# Use a secure way to get host/port in production
host = os.environ.get('FLASK_HOST', '127.0.0.1')
port = int(os.environ.get('FLASK_PORT', 5000))
app.run(host=host, port=port)