Adds GraphQL support to your Sanic application.
Based on flask-graphql by Syrus Akbary.
Just use the GraphQLView view from sanic_graphql
from sanic_graphql import GraphQLView
app.add_route(GraphQLView.as_view(schema=Schema, graphiql=True), '/graphql')
# Optional, for adding batch query support (used in Apollo-Client)
app.add_route(GraphQLView.as_view(schema=Schema, batch=True), '/graphql/batch')This will add /graphql endpoint to your app.
In order to pass Sanic’s eventloop to GraphQL’s AsyncioExecutor, use before_start listener:
@app.listener('before_server_start')
def init_graphql(app, loop):
app.add_route(GraphQLView.as_view(schema=Schema, executor=AsyncioExecutor(loop=loop)), '/graphql')schema: TheGraphQLSchemaobject that you want the view to execute when it gets a valid request.context: A value to pass as thecontextto thegraphql()function. By default is set todictwith request object at keyrequest.root_value: Theroot_valueyou want to provide toexecutor.execute.pretty: Whether or not you want the response to be pretty printed JSON.executor: TheExecutorthat you want to use to execute queries. If anAsyncioExecutorinstance is provided, performs queries asynchronously within executor’s loop.graphiql: IfTrue, may present GraphiQL when loaded directly from a browser (a useful tool for debugging and exploration).graphiql_template: Inject a Jinja template string to customize GraphiQL.jinja_env: Sets jinja environment to be used to process GraphiQL template. If Jinja’s async mode is enabled (byenable_async=True), usesTemplate.render_asyncinstead ofTemplate.render. If environment is not set, fallbacks to simple regex-based renderer.batch: Set the GraphQL view as batch (for using in Apollo-Client or ReactRelayNetworkLayer)
You can also subclass GraphQLView and overwrite get_root_value(self, request) to have a dynamic root value per request.
class UserRootValue(GraphQLView):
def get_root_value(self, request):
return request.userCopyright for portions of project sanic-graphql are held by Syrus Akbary as part of project flask-graphql. All other copyright for project sanic-graphql are held by Sergey Porivaev.
This project is licensed under MIT License.