Graphql in python using graphene

In this guide, we’ll explain how to integrate GraphQL into Python projects. You’ll learn how to set up a GraphQL server, define schema, and write queries and mutations with practical examples. Whether you're building a new application or enhancing an existing one, this guide will give you the tools and knowledge to leverage GraphQL effectively with Python.

To know about key terminologies used in graphql, you can read it here: Key terms used in GraphQL

In this guide, we will go step by step from scratch.

Open terminal or command prompt based on your OS and create a working directory and go inside the directory

mkdir graphql_with_python
cd graphql_with_python


Create a virtualenv and activate the virtualenv. If you want a guide about this, visit venv — Creation of virtual environments

python -m venv .venv
source .venv/bin/activate # for linux/macos
.venv\Scripts\activate # for windows


To work with GraphQL in Python, we have to install graphene library. Open your terminal/command prompt and

pip install graphene


Now, create a schema.py file in our working directory, graphql_with_python/schema.py and create a type named Book with two fields title and author. (Although, we don't need this class now, we will use it later for Mutation class and when we write query to list Book objects.)

import graphene 

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


Now create a simple query class named Query in schema.py file

class Query(graphene.ObjectType):
    hello_world = graphene.String() # Field

    def resolve_hello(self): # resolver function
        return "Hello World from graphene"

Here hello_world is a field and resolve_hello_world() is resolver function for hello_world field. Resolver function's name should be resolve_<field_name>.

Now, we will create schema in schema.py file.

schema = graphene.Schema(query=Query)


Now we will write query. For this, we will create a new file named query.py in our working directory, graphql_with_python/query.py.

from schema import schema

query1 = '''
    query helloB{
        helloWorld
    }
'''

result = schema.execute(query1)
print(result.data)
  • In first block query helloB{}, we use word query to make this request a query request and name helloB is the name for that query and it can be named anything. But for helloWorld, its name should come from field hello_world from Query class. Here, hello_world in snake_case is converted to helloWorld in pascalCase.

You can run query.py file on terminal/command prompt to see the result

python query.py


Now, we will create a class CreateBook, which inherits graphene.Mutation, and it handles mutation request for Book type.

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

    book = graphene.Field(Book) # field

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


Now, we will create Mutation class, which will contain fields to handle mutations

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


Now, we add Mutation class to schema

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


Now, we create new mutation operation and store it on variable mutation1 on graphql_with_python/query.py file.

mutation1 = '''
    mutation bookCreator{
        createBook(title: "The Greate Gatsby", author: "Not Buddhi Sagar"){
            book {
                title
                author
            }
        }
    }
'''

result = schema.execute(mutation1)
print(result.data)
  • First block, mutation bookCreator{}, means this request is of type mutation and bookCreator is name for this mutation request. You can name this request anything.
  • In second block, createBook(title: "Karnali Green", author: "Not Buddhi Sagar"){}, createBook names come from create_book field of Mutation class. Here, create_book in snake_case is converted to createBook in camelCase and value for arguments are provided.
  • Third block, book{ title author}, returns Book object with title and author field

Now, add one more field to Query. Here we will add a field to return objects of Book class. Now our Query class with updated code looks like this

class Query(graphene.ObjectType):
    hello_world = graphene.String() 
    books = graphene.List(Book) # Field added

    def resolve_hello_world(self, info): 
        return "Hello World from graphene"

    def resolve_books(self, info): # resolver for books added
        import gc # garbace collector

        # dummy objects
        b1 = Book(title="Seto Dharti", author="Amar Neuapane")
        b2 = Book(title="Karnali Blues", author="Buddhi Sagar")

        obj_list = []
        for obj in gc.get_objects():
            if isinstance(obj, Book):
                obj_list.append(obj)

        return obj_list


Also, add query_books variable with query request on graphql_with_python/query.py file.

query_books = '''
    query bookList{
        books{
            title
            author
        }
    }
'''

result = schema.execute(query_books)
print(result.data)



In case of confusion, our final graphql_with_python/schema.py file looks like this:

import graphene


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


class Query(graphene.ObjectType):
    hello_world = graphene.String() # Field
    books = graphene.List(Book) # Field added

    def resolve_hello_world(self, info): # resolver function
        return "Hello World from graphene"

    def resolve_books(self, info): # resolver for books added
        import gc # garbace collector

        # dummy objects
        b1 = Book(title="Seto Dharti", author="Amar Neuapane")
        b2 = Book(title="Karnali Blues", author="Buddhi Sagar")

        obj_list = []
        for obj in gc.get_objects():
            if isinstance(obj, Book):
                obj_list.append(obj)

        return obj_list


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

    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)


And graphql_with_python/query.py file looks like this.

from schema import schema

query1 = '''
    query helloB{
        helloWorld
    }
'''

mutation1 = '''
    mutation bookCreator{
        createBook(title: "The Greate Gatsby", author: "Not Buddhi Sagar"){
            book {
                title
                author
            }
        }
    }
'''

query_books = '''
    query{
        books{
            title
            author
        }
    }
'''

result = schema.execute(query_books)
print(result.data)


To read more about graphene, visit Graphene Documentation.