Using GraphQL with Python

Loading

GraphQL is a query language for APIs that provides flexibility, efficiency, and precise data fetching. Unlike REST APIs, where multiple endpoints are needed for different data, GraphQL allows clients to request only the data they need in a single query.

Python supports GraphQL through libraries like Graphene, Ariadne, and Strawberry. In this guide, we’ll cover:
Setting up a GraphQL API with Graphene
Defining schemas and resolvers
Running GraphQL queries and mutations
Integrating GraphQL with a database


1. Installing GraphQL Libraries

To get started, install Graphene (a popular GraphQL library for Python):

pip install graphene graphene-django Flask flask-graphql
  • Graphene → Core GraphQL library for Python
  • Flask → Lightweight web framework
  • Flask-GraphQL → Integrates GraphQL with Flask

2. Setting Up a Basic GraphQL Server

Step 1: Create a Basic GraphQL Schema

Create a file schema.py to define the GraphQL schema.

import 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)

Here,
hello field → Takes an optional name argument
resolve_hello method → Returns a greeting


3. Creating a GraphQL API with Flask

Create a file app.py and set up a Flask server to expose the GraphQL API.

from flask import Flask
from flask_graphql import GraphQLView
from schema import schema # Import schema from schema.py

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)

Now, run the Flask app:

python app.py

Visit http://127.0.0.1:5000/graphql in your browser to access the GraphiQL interface.


4. Running GraphQL Queries

Use the GraphQL Playground to test queries.

Basic Query

{
hello(name: "Narendra")
}

Response

{
"data": {
"hello": "Hello, Narendra!"
}
}

5. Defining More Complex Queries

Let’s add a Book type and return a list of books.

Modify schema.py

class Book(graphene.ObjectType):
title = graphene.String()
author = graphene.String()

class Query(graphene.ObjectType):
books = graphene.List(Book)

def resolve_books(self, info):
return [
Book(title="1984", author="George Orwell"),
Book(title="The Alchemist", author="Paulo Coelho"),
]

schema = graphene.Schema(query=Query)

Query Books

{
books {
title
author
}
}

Response

{
"data": {
"books": [
{"title": "1984", "author": "George Orwell"},
{"title": "The Alchemist", "author": "Paulo Coelho"}
]
}
}

6. Adding Mutations (Insert, Update, Delete)

Mutations allow clients to modify data.

Define a Mutation

Modify schema.py to add a create_book mutation.

class CreateBook(graphene.Mutation):
class Arguments:
title = graphene.String()
author = graphene.String()

book = graphene.Field(Book)

def mutate(self, info, title, author):
book = Book(title=title, author=author)
return CreateBook(book=book)

class Mutation(graphene.ObjectType):
create_book = CreateBook.Field()

schema = graphene.Schema(query=Query, mutation=Mutation)

Run a Mutation

mutation {
createBook(title: "The Great Gatsby", author: "F. Scott Fitzgerald") {
book {
title
author
}
}
}

Response

{
"data": {
"createBook": {
"book": {
"title": "The Great Gatsby",
"author": "F. Scott Fitzgerald"
}
}
}
}

7. Integrating GraphQL with a Database (SQLite & SQLAlchemy)

GraphQL works well with databases like PostgreSQL, MySQL, and SQLite using SQLAlchemy.

Step 1: Install Dependencies

pip install sqlalchemy graphene-sqlalchemy

Step 2: Define Models (models.py)

from sqlalchemy import Column, Integer, String, create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

Base = declarative_base()

class BookModel(Base):
__tablename__ = "books"

id = Column(Integer, primary_key=True)
title = Column(String)
author = Column(String)

engine = create_engine("sqlite:///books.db")
Base.metadata.create_all(engine)

Session = sessionmaker(bind=engine)
session = Session()

Step 3: Connect SQLAlchemy with GraphQL (schema.py)

import graphene
from graphene_sqlalchemy import SQLAlchemyObjectType
from models import BookModel, session

class Book(SQLAlchemyObjectType):
class Meta:
model = BookModel

class Query(graphene.ObjectType):
books = graphene.List(Book)

def resolve_books(self, info):
return session.query(BookModel).all()

schema = graphene.Schema(query=Query)

Now, GraphQL queries will fetch data directly from SQLite.

Leave a Reply

Your email address will not be published. Required fields are marked *