How to Use GraphQL With Django

Is GraphQL the future?

Figure 1 — Credits

GraphQL is a query language for APIs that gives clients the ability to ask exactly what they need from APIs. In this post, we will explore GraphQL and how to use it with Django (Python web framework). Let’s take a tour.


$ pip install Django
$ pip install graphene-django

Set up the Django project

We need to create our Django project:

  • A Django project called bookstore
  • An app within bookstore called books
$ django-admin startproject bookstore
$ cd bookstore
$ django-admin startapp books

We need to add graphene_django and bookstore.booksto the INSTALLED_APPS in the of our Django project:


Defining our models

A model is the single, definitive source of information about our data. Each model maps to a single database table. We will use an SQLite database for an online bookstore for inventory and sale database/bookstore.db

from django.db import models
class Publisher(models.Model):
id = models.AutoField(primary_key=True)
p_name = models.CharField(max_length=40)
city = models.CharField(max_length=20)
zip = models.CharField(max_length=10)
class Meta:
managed = False
db_table = 'Publisher'

class Book(models.Model):
id = models.CharField(max_length=20, primary_key=True)
pub = models.ForeignKey('Publisher', models.DO_NOTHING)
title = models.CharField(max_length=100)
price = models.FloatField()
category = models.CharField(max_length=30, null=True)
quantity = models.IntegerField()
b_format = models.CharField(max_length=40, null=True)
prod_year = models.IntegerField()
filesize = models.IntegerField(blank=True, null=True)
class Meta:
managed = False
db_table = 'Book'
  • Add a graphql URL to the of your Django project:
from django.urls import path
from graphene_django.views import GraphQLView

urlpatterns = [
path("graphql", csrf_exempt(GraphQLView.as_view(graphiql=True, schema=schema))),

The CSRF middleware and template tag provides easy-to-use protection against Cross-Site Request Forgeries.

  • Define the schema location for Graphene in our Django project settings:
'SCHEMA': 'bookstore.books.schema'

In order to make GraphQL queries, we need :

  • Schema with defined object types.
  • A view, taking queries as input and returning the result.

The schema books/ should include two classes named Query and Mutation those extend all the schemas from your apps.


Queries are strings that are sent to the server to be interpreted and executed, and they then return JSON data back to the client. Here we have a query that would return a list of all of the books and publishers stored in the database.

import graphene
from graphene import ObjectType, Schema, Mutationfrom graphene_django import DjangoObjectType
from bookstore.books.models import Publisher, Book
class PublisherType(DjangoObjectType):
class Meta:
model = Publisher
fields = ("id", "p_name", "city", "zip")
class BookType(DjangoObjectType):
class Meta:
model = Book
fields = ("id", "pub", "title", "price", "category", "quantity", "b_format", "prod_year", "filesize")
class Query(ObjectType):
all_book = graphene.List(BookType)
all_publisher = graphene.List(PublisherType)


In order to respond to queries, a schema needs to have resolvers for all fields. Resolvers are a collection of functions that generate responses for a GraphQL query.

def resolve_all_book(self):
return Book.objects.all()
def resolve_all_publisher(self):
return Publisher.objects.all()

Example for a publishers query:

How to Use GraphQL With Django was originally published in Better Programming on Medium, where people are continuing the conversation by highlighting and responding to this story.

(Visited 1 times, 1 visits today)