Warning: Bocadillo is now UNMAINTAINED. Users are recommended to migrate to a supported alternative, such as Starlette or FastAPI. Please see #344 for more information.

GraphQL with Tartiflette

GraphQL is an API query language, often presented as a complement to regular REST API endpoints. The GraphQL documentation reads:

GraphQL [...] gives clients the power to ask for exactly what they need and nothing more, makes it easier to evolve APIs over time, and enables powerful developer tools.

If you want to add a GraphQL endpoint to Bocadillo, all you need is an async GraphQL engine that provides an ASGI adapter. Options include Ariadne and Tartiflette.

In this guide, we will be using:

  • Tartiflette: a Python asynchronous GraphQL engine built on libgraphqlparser.
  • tartiflette-starlette: an ASGI wrapper for Tartiflette featuring a built-in GraphiQL client.

SEE ALSO

  • For an introduction to GraphQL, read the official Introduction to GraphQL.
  • For a complete example project using Tartiflette and tartiflette-starlette, including a React frontend using the React Apollo client, see the react-example example project.

Project setup

Setting up your project to serve a GraphQL API is as simple as mounting a TartifletteApp as a nested app:

  1. Install Tartiflette and tartiflette-starlette:
pip install tartiflette tartiflette-starlette
  1. Create an ASGI TartifletteApp out of your Tartiflette engine or sdl string (if these concepts sound unfamiliar, see the Tartiflette documentation):
# myproject/graphql.py
from tartiflette import Engine, Resolver
from tartiflette_starlette import TartifletteApp

@Resolver("Query.hello")
async def hello(parent, args, ctx, info):
    return "Hello, GraphQL!"

engine = Engine("type Query { hello: String }")
graphql = TartifletteApp(engine=engine)
  1. Mount it as a nested app and register the startup event handler:


 


 


# myproject/app.py
from bocadillo import App
from .graphql import graphql

app = App()
app.mount("/graphql", graphql)
app.on("startup", graphql.startup)
  1. Serve the app, and make your first query!
curl -H "Content-Type: application/graphql" http://localhost:8000
{ "data": { "hello": "Hello, GraphQL!" } }

🚀

Interactive GraphiQL client

The GraphiQL client can be enabled using the graphiql option to TartifletteApp. We recommend using a setting to provision this option:

# myproject/settings.py
GRAPHIQL = True  # Modify to your liking
# myproject/graphql.py
from . import settings
# ...
graphql = TartifletteApp(engine=engine, graphiql=settings.GRAPHIQL)

It will be accessible on the same endpoint than the regular GraphQL API, e.g. http://localhost:8000/graphql.

Building the API

Once you've completed the above steps, you're in Tartiflette territory! Building the GraphQL API is simply a matter of writing queries, resolvers and mutations.

You can learn more about these concepts here:

For more information on using TartifletteApp, see the tartiflette-starlette documentation.