GraphQL

FastAPI has optional support for GraphQL (provided by Starlette directly), using the graphene library.

You can combine normal FastAPI path operations with GraphQL on the same application.

Import and use graphene

GraphQL is implemented with Graphene, you can check Graphene's docs for more details.

Import graphene and define your GraphQL data:

import graphene
from fastapi import FastAPI
from starlette.graphql import GraphQLApp


class Query(graphene.ObjectType):
    hello = graphene.String(name=graphene.String(default_value="stranger"))

    def resolve_hello(self, info, name):
        return "Hello " + name


app = FastAPI()
app.add_route("/", GraphQLApp(schema=graphene.Schema(query=Query)))

Add Starlette's GraphQLApp

Then import and add Starlette's GraphQLApp:

import graphene
from fastapi import FastAPI
from starlette.graphql import GraphQLApp


class Query(graphene.ObjectType):
    hello = graphene.String(name=graphene.String(default_value="stranger"))

    def resolve_hello(self, info, name):
        return "Hello " + name


app = FastAPI()
app.add_route("/", GraphQLApp(schema=graphene.Schema(query=Query)))

Info

Here we are using .add_route, that is the way to add a route in Starlette (inherited by FastAPI) without declaring the specific operation (as would be with .get(), .post(), etc).

Check it

Run it with Uvicorn and open your browser at http://127.0.0.1:8000.

You will see GraphiQL web user interface:

More details

For more details, including:

  • Accessing request information
  • Adding background tasks
  • Using normal or async functions

check the official Starlette GraphQL docs.