GraphQL Server in Python with Graphene
Graphene is a Python library for building GraphQL APIs. It provides a simple and elegant way to define GraphQL schemas, queries, and mutations using Python classes.
Installation
Install Graphene and Flask (or another web framework):
Basic Setup
Create a file called app.py
:
from flask import Flask
from graphene import ObjectType, String, Schema
from flask_graphql import GraphQLView
class Query(ObjectType):
hello = String(name=String(default_value="World"))
def resolve_hello(root, info, name):
return f"Hello, {name}!"
schema = Schema(query=Query)
app = Flask(__name__)
app.add_url_rule(
"/graphql",
view_func=GraphQLView.as_view("graphql", schema=schema, graphiql=True),
)
if __name__ == "__main__":
app.run(debug=True)
Visit http://localhost:5000/graphql
to try it in GraphiQL.
Defining Types
Define your GraphQL types using Python classes.
import graphene
class User(graphene.ObjectType):
id = graphene.ID()
name = graphene.String()
email = graphene.String()
Query with Fields
class Query(graphene.ObjectType):
user = graphene.Field(User, id=graphene.ID(required=True))
def resolve_user(root, info, id):
# Example: return fake data
return User(id=id, name="Alice", email="alice@example.com")
Mutations
Define mutations with graphene.Mutation
:
class CreateUser(graphene.Mutation):
class Arguments:
name = graphene.String(required=True)
email = graphene.String(required=True)
user = graphene.Field(lambda: User)
def mutate(root, info, name, email):
user = User(id="1", name=name, email=email)
return CreateUser(user=user)
class Mutation(graphene.ObjectType):
create_user = CreateUser.Field()
Add it to the schema:
Using Input Types
class UserInput(graphene.InputObjectType):
name = graphene.String(required=True)
email = graphene.String(required=True)
class CreateUser(graphene.Mutation):
class Arguments:
input = UserInput(required=True)
user = graphene.Field(User)
def mutate(root, info, input):
return CreateUser(user=User(id="2", name=input.name, email=input.email))
Middleware & Context
You can pass custom context for auth, DB access, etc.:
app.add_url_rule(
"/graphql",
view_func=GraphQLView.as_view(
"graphql",
schema=schema,
graphiql=True,
get_context=lambda: {"current_user": get_current_user()},
),
)
Integrations
Graphene can be used with various backends:
- Django: Graphene-Django
- SQLAlchemy: Use with graphene-sqlalchemy
- Ariadne: For SDL-first approach
Pros & Cons
✅ Pros
- Pythonic and class-based
- Works with Flask, Django, FastAPI
- Good for small to medium-sized APIs
- Easy to prototype
❌ Cons
- Resolver performance may require optimization
- Smaller ecosystem than JavaScript-based tools
- Lacks advanced real-time/subscription support out of the box
Resources
Summary
Graphene is a solid choice for building GraphQL servers in Python. It’s easy to get started with and integrates well with popular Python frameworks like Flask and Django. Ideal for teams already working in Python ecosystems.