Adds GraphQL support to your FastAPI application.
Install with:
pip install graphql-server[fastapi]
Use the GraphQLRouter from graphql_server.fastapi.
from fastapi import FastAPI
from graphql_server.fastapi import GraphQLRouter
from schema import schema
app = FastAPI()
graphql_app = GraphQLRouter(schema=schema, graphiql=True)
app.include_router(graphql_app, prefix="/graphql")CORS
Use FastAPI's
CORSMiddlewareto enable cross-origin requests:from fastapi.middleware.cors import CORSMiddleware app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"], )
schemapathgraphiqlgraphql_ideallow_queries_via_getkeep_alivekeep_alive_intervaldebugroot_value_gettercontext_gettersubscription_protocolsconnection_init_wait_timeoutmultipart_uploads_enabled
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.userYou can also subclass GraphQLRouter and overwrite get_root_value(self, request) to have a dynamic root value per request.
class UserRootValue(GraphQLRouter):
def get_root_value(self, request):
return request.userSee CONTRIBUTING.md