Building GraphQL API with Python & Django Part #2: Setting up Server & Schema

In this tutorial, you will set up the GraphQL server and implement your first GraphQL query.


In this section, you will set up the project for your GraphQL server and implement your first GraphQL query. We will be doing the following in this tutorial:
  • Setting up a development environment
  • Setting up Django Project
  • Defining the GraphQL Schema
. . .

Setting up Dev environment

Before starting, make sure you have Python 3.7 installed. If not, you can download it here. The installation is pretty straightforward on any supported operating system.

When working with Python, you will use Virtual Environment: a tool for keeping all the project’s dependencies isolated from your system – or other projects.
In the terminal, create a new virtual environment and activate it, let's create the virtual environment with the following command:
python3.6 -m venv ve

You’ll notice your prompt changed to (ve) .... It means you are inside your virtual environment, every Python package will be installed there. If you want to leave it, just type deactivate.
source ve/bin/activate

. . .

Set up the Django project

First, we need to install the dependencies. The tool used to manage Python packages is pip, which should be available with your Python installation.
pip install Django==3.0.5 django-channels-graphql-ws==0.5.0 graphene-django==2.9.1 django-graphql-jwt==0.3.1 django-graphql-playground==1.0

Now we have installed the dependencies, lets setup the Django Application. We will set up the project, create the following:
  • A Django project called pythonSWAPI
  • An app within pythonSWAPI called swapi
# Set up a new project with a single application
django-admin.py startproject pythonSWAPI
cd pythonSWAPI
django-admin.py startapp swapi
Now sync your database for the first time:
python manage.py migrate
Let's run the server:
python manage.py runserver
The commands above will install the necessary libraries, create a new Django project, create the base Django tables and start its built-in webserver. To test it, open your browser and access the http://localhost:8000 address. You should see the following page:

Now we have successfully bootstrapped the django project & its listening on port 8000.
. . .

Defining Schema

In order to make queries to our Django project, we are going to need few things:
  • Schema with defined object types
  • A view, taking queries as input and returning the result

GraphQL presents your objects to the world as a graph structure rather than a more hierarchical structure to which you may be accustomed. In order to create this representation, Graphene needs to know about each type of object which will appear in the graph. This graph also has a root type through which all access begins. This is the Query class below. This means, for each of our models, we are going to create a type, subclassing DjangoObjectType After we’ve done that, we will list those types as fields in the Query class. Lets create the schema for our application as follows

import graphene

# 1
class Query(graphene.ObjectType):
# 2
hello = graphene.String()
# 3
def resolve_hello(self, info, **kwargs):
return "world"

#4
schema = graphene.Schema(query=Query)

Let's walk through the comments to understand the code
  1. We have defined our root query which has only one query
  2. We have defined one query as "hello" which returns the string
  3. A resolver function to resolve the "hello" query
  4. We have exported the GraphQL Schema
. . .

Configuring Graphene Django

Add the graphene-django and our application into the installed apps, search for the INSTALLED_APPS variable and add the following:

INSTALLED_APPS = [
# Other apps
'graphene_django',
'swapi', # Install the swapi app
]
And add following at the bottom of the file pythonSWAPI/settings.py file:

GRAPHENE = { 'SCHEMA': 'swapi.schema.schema', }
Unlike a RESTful API, there is only a single URL from which GraphQL is accessed. Requests to this URL are handled by Graphene’s GraphQLView view. This view will serve as GraphQL endpoint. As we want to have the aforementioned GraphiQL we specify that on the parameters with graphiql=True. Edit p[ythonSWAPI/urls.py as follow:

from django.conf.urls import url, include
from django.contrib import admin

from graphene_django.views import GraphQLView

from swapi.schema import schema

urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^graphql$', GraphQLView.as_view(graphiql=True, schema=schema)),
]
. . .

Testing Our API

To test our API, let's run the project and then go to the GraphQL endpoint. In the terminal type:
python manage.py runserver
Once your server is running head to http://127.0.0.1:8000/graphql/. You'll encounter GraphiQL- a built in IDE to run your queries!


Congratulations, you just implemented and successfully tested your first GraphQL query 🎉
. . .

A word on the GraphQL schema

At the core of every GraphQL API, there is a GraphQL schema. So, let’s quickly talk about it.

Note: In this tutorial, we’ll only scratch the surface of this topic. If you want to go a bit more in-depth and learn more about the GraphQL schema as well as its role in a GraphQL API, be sure to check out this excellent article.
GraphQL schemas are usually written in the GraphQL Schema Definition Language (SDL). The SDL has a type system that allows defining data structures (just like other strongly typed programming languages such as Java, TypeScript, Swift, Go, …).
. . .
In the next tutorial, we will be extending our schema & will add more queries to GraphQL API.



Sumit Sharma

Jun 25 2019

Write your response...

On a mission to build Next-Gen Community Platform for Developers