GraphQL Server for Python

3.0.0 · active · verified Fri Apr 17

graphql-server is a Python library that provides integrations for setting up GraphQL servers in various web frameworks such as Flask, Starlette, Django, and Sanic. It currently includes version 3.0.0, which acts as a meta-package bundling core server logic and framework-specific adapters. Releases are made as needed, often in conjunction with updates to its underlying `graphql-core` and framework integration packages.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates setting up a basic GraphQL server with Starlette and `graphql-server-starlette`. It defines a simple schema using `graphene`, then exposes it via `GraphQLRouter` at `/graphql` and a GraphQL Playground UI at `/graphql-playground`. You'll need `starlette`, `uvicorn`, `graphene`, and `graphql-server` installed.

import graphene
from starlette.applications import Starlette
from starlette.responses import JSONResponse
from starlette.routing import Route
from graphql_server.starlette import GraphQLRouter

# 1. Define your GraphQL schema using Graphene
class Query(graphene.ObjectType):
    hello = graphene.String(name=graphene.String(default_value="World"))

    def resolve_hello(self, info, name):
        return f"Hello, {name}!"

schema = graphene.Schema(query=Query)

# 2. Integrate with Starlette using GraphQLRouter
async def homepage(request):
    return JSONResponse({"message": "Visit /graphql for the API or /graphql-playground for the UI."}) 

routes = [
    Route("/", homepage),
    Route("/graphql", GraphQLRouter(schema)),
    Route("/graphql-playground", GraphQLRouter(schema, playground=True))
]

app = Starlette(routes=routes)

# To run this app, save it as `app.py` and execute:
# uvicorn app:app --reload
# Then visit http://127.0.0.1:8000/graphql-playground in your browser.

view raw JSON →