GraphQL with Django — a tutorial that works

Muhammad Dauda
4 min readJul 17, 2018

--

GraphQL Logo

If you don’t know what GraphQL is, its a query language that gives clients the power to ask for exactly what they need from API’s, nothing more,nothing less. This makes it possible to get predictable results. Apps using GraphQL are fast and stable because they control the data they get, not the server.

Lets assume we have a model named ‘User’ and we wish to get the list of users. By sending this simple & flexible GraphQL query to our API:

{
users {
id
name
gender
}
}

we get the following response:

{
"users": [
{
"id": "1",
"name": "Blue Rook",
"gender": "male"
},
{
"id": "2",
"name": "Xiao Tian",
"gender": "female"
}
]
}

Awesome right? ;)

I decided to write this tutorial because it didn’t seem rational to just watch others go through the same trouble i had to face, jumping back and forth from one tutorial to another.

Most of the tutorials i had to go through didn’t seem straight forward at all and i had to try a lot of things that didn’t seem to work, but the moment i got my Code working i realized that Setting up GraphQL with Django was fairly easy. Kapish!

Lets get started!

Since this is a GraphQL tutorial i woun’t go through the steps of setting up a Django project, so am guessing you already have a Django project up and running. However, we are going to create a new app to play around with.

You can get the whole project from https://github.com/alhajee/Django-GraphQL-tutorial/tree/master/tutorial_part1

Now you need to install Graphene, a library for building GraphQL APIs in Python. We also need to install graphiql, it’s a library which makes it easier to test, explore and experiment with the API.

Step 1 — Installation

From your console, use pip to install graphene and graphiql

pip install graphene-djangopip install django-graphiql

Step 2 — Create your App

Assuming you haven’t already created an App, create a new App; Hero app. It’s simply going to contain information on our top 10 heroes :)

python manage.py startapp hero

Step 3 — Create your Models

With this app in place, we need to define our model in hero/models.py

from django.db import modelsclass Hero(models.Model):    name = models.CharField(max_length=100)    gender = models.CharField(max_length=100, choices=(('M', 'Male'), ('F', 'Female')), default='F')    movie = models.CharField(max_length=100)

Now, Lets migrate our new Model

python manage.py makemigrations
python manage.py migrate

From the terminal lets runpython manage.py shell and populate the model with a few test data

from .models import Hero
Hero.objects.create(name='Doctor Doom', gender='M', movie='Fantastic Four')
Hero.objects.create(name='Magneto', gender='M', movie='X-men')
Hero.objects.create(name='Mystique', gender='F', movie='X-men')

Now our database is populated with three objects

In our settings.py Let’s to add graphene and our hero app to the list of installed apps:

INSTALLED_APPS = (
# ...
'hero',
'graphene_django',
)

Step 4 — Create an App level schema

A Schema is simply a file that translates your models to GraphQL, it tells it the nature of your models and how it should interact with them.

New, lets create a schema file for graphene in the app hero/schema.py

In GraphQL, a Type is an object that represents your model, you can tailor it to let you filter your results based on a criteria (We will look at how we can use filters in our next tutorial). .

A collection of types forms the schema, and every schema has a special class called Query, used for getting data from the server, and Mutation for sending data to the server. Each field in our type is calculated through resolvers that returns values.

If the new terms are starting to seem confusing, just keep in mind that Types are just GraphQL’s equivalent for models.

import graphene
from graphene_django import DjangoObjectType
from .models import Hero
class HeroType(DjangoObjectType):
class Meta:
model = Hero
class Query(graphene.ObjectType):
heroes = graphene.List(HeroType)
def resolve_heroes(self, info, **kwargs):
return Hero.objects.all()

We created an class HeroType which is an Object that represents our model, and then a resolver resolve_heroes that returns the value of a field.

Step 5 — Create a project level schema

The above schema is an app level schema, so we will have to create a project level schema schema.py . It’s way you have to create a project level and app level urls.py file in Django.

The good side to this is that we can connect our end-point to as many apps as we want and they will still be accessible globally in the project. This keeps our API scalable.

import grapheneimport hero.schema
class Query(hero.schema.Query, graphene.ObjectType):
pass
schema = graphene.Schema(query=Query)

Step 6 — Add GraphQL to Settings

Don’t forget to add GraphQL to oursettings.py file

GRAPHENE = {
‘SCHEMA’: ‘src.schema.schema’
}

Step 7 — Add GraphQL to Urls

Next, add GraphQL to the project’s urls.py

from django.urls import path
from graphene_django.views import GraphQLView
from .schema import schema
urlpatterns = [
# ...
path('graphql/', GraphQLView.as_view(schema=schema, graphiql=True)),
]

Kapish !!!

Now lets test our API using graphiql interface by opening http://localhost:8000/graphql/ in our browser

I will appreciate any feedback. Please be sure to leave comments. I hope this post was helpful :)

Complete project: https://github.com/alhajee/Django-GraphQL-tutorial/tree/master/tutorial_part1

Credits: [‘https://www.howtographql.com/graphql-python/2-queries/’, ‘https://gearheart.io/blog/how-to-use-graphql-with-django-with-example/’, ‘https://github.com/graphql-python/graphene-django/’]

--

--