Diving head first into GraphQL — Part 2


In this series, we explore the core concepts of GraphQL, with implementations in both Javascript and Python. In the previous section we discussed why GraphQL is preferred over REST and can be accessed here.

In this part we shall build GraphQL Servers. GraphQL servers enable us to fetch data from multiple sources such as REST, SQL, NoSQL databases with a single request and endpoint. For this particular section we shall only consume data from a REST API.

The final code in this section can be accessed here.

Setting up the REST API.

We shall set up a full fledged fake REST API under 60 seconds which we shall use through out this series. It is assumed that node is already installed on the system. This step needs to be done by both Python and Javascript ninjas since the same REST API will be used in both implementations.

  1. Create an empty directory Diving-into-GraphQL
  2. Change into that directory and run npm init follow through the prompts
  3. Lets install json-server and json-server-init

json-server — Fully fledged fake REST API
json-server-init — Generates dummy information to be stored in the database

npm install json-server 
npm install -g json-server-init

4. Edit the package.json file and add following line.

"scripts": {
"json-server": "json-server --watch db.json"

5. Generate some data for our database using json-server-init package.

// in the terminal run
json-server-init create

5a. Follow the prompts and enter the collection name and number of entries e.g users 5

5b. Specify the fields the collection will have in my case I used the following id:index, email:email, username:username, teamId:number|2, address:addressObject

5c. After this another prompt will show up asking to add another collection. Select Yes and lets add our final collection. Repeat step 5a. using teams 2 as the input.

Specify fields for the teams collection as follows
id:number|2, profile:lorem, name:business

With this step complete, select you don’t want to add any more collections and file db.json will be created which will serve as our database.

6. Finally run npm run json-server . Now we can make http requests to our json-server athttp://localhost:3000/users

Now that we have the REST API server we can revisit the GraphQL Core concepts.

GraphQL Core Concepts

The first concept to be discussed are Schemas. Think of schemas as the contract between the GraphQL server and the GraphQL Client. They explicitly describe the data types to be returned, they also specify how the client is to query for data.

Schemas specify the types definitions of the data to be returned. This feature aids backend and frontend teams to work separately seamlessly. Since the data types are clearly defined.

Schemas describe a root query this serves as the entry point for GraphQL to traverse the graph of data and they provide us a format to query for data.

Lastly resolvers, these specify where to fetch the required data from, this can be a REST endpoint, SQL database, NoSQL database or any other for data source.

Type definitions, Queries and resolvers are what’s required to build a GraphQL server in any language. Lets build a GraphQL server in JavaScript. Pythonistas can skip this section and jump straight to the Python section.

GraphQL Server with JavaScript

Project Setup

We shall need to setup and configure Babel so as to use ES6+ Javascript

npm install —save-dev babel-cli babel-preset-env babel-preset-stage-2, nodemon, eslint

Setup eslint since linting is always a great idea and helps eliminate useless mental effort.

eslint --init

Select popular configuration airbnb 
Finally update the package.json file

"scripts": {
. . .
"start": "nodemon --watch server --watch package.json js-server/index.js --exec babel-node —-presets env,stage-2"

Define the Schema

In the path js-server/data/schema.js add the following code

Inspecting the above code we see that for every type Object there is a data type specified. The exclamation mark ensures that a field is non null. The [] denotes that we expect an array of objects to be returned.

The above code also defines a type Query which shows how we should request for data and any arguments that might be required by the Query

Resolver Functions
In the path js-server/data/resolvers.js add the following code.

Resolver functions map the keys in the Query object to functions that return the required data.

Resolvers functions can also map keys in type definitions to functions that also return that data for example line 10–12 in resolvers.js returns the matching team for User object.

GraphQL Server
Lets install the dependencies needed to finalize the GraphQL server

  • express — Fast, unopinionated, minimalist web framework for node.
  • graphql — JavaScript reference implementation for GraphQL
  • graphql-server-express — Express integration of GraphQL Server
  • graphql-tools — Useful tools to create and manipulate GraphQL schemas
  • axios — Promise based HTTP client for the browser and node.js
  • body-parser — Node.js body parsing middleware
npm install express graphql graphql-server-express graphql-tools axios body-parser

In the path js-server/index.js add the following code.

Ensure that the REST Client created earlier is running npm run json-server and then run the GraphQL Server withnpm start

GraphQL servers come with graphiql which is a development GraphQL client to be used to inspect our queries. It can be accessed from the link below.

Declarative fetching of data using GraphiQL client.

GraphQL Server with Python

Project Setup
Create a folder python-server and setup a virtual environment

virtualenv -python=python3 venv

Install the dependencies required for the GraphQL server

  • Flask — minimalist web framework for python
  • Flask-GraphQL — GraphQL connection with Flask framework
  • Graphene — Python implementation of GraphQL
  • Requests — Python library for making http requests

Activate the virtualenv and install the above dependencies

pip install flask graphene requests flask-graphql

Define the Schema
Inspecting the code below we see that for every field in the classes there is a data type specified.

The code also defines a classQuery which shows how we should request for data and any arguments that might be required by the Query. The resolver functions are also placed within the classes to fetch the required data.

The following code is located in path python-server/data/schema.py

GraphQL Server

Ensure that the REST API is running and run the python GraphQL server with python app.py in the terminal.

GraphQL servers come with graphiql which is a development GraphQL client to be used to inspect our queries. It can be accessed from the link below.


The final code can be accessed here.

Demo of making queries to our GraphQL server using GraphiQL Client

Declarative fetching of data using GraphiQL client

Till next time, never stop learning.

Like what you read? Give Paul Nyondo a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.