A Beginner’s Guide to GraphQL

A Beginner’s Guide to GraphQL

Introduction to GraphQL for beginners. Learn about GraphQL, how it works step by step.

One of the most commonly discussed terms today is the API. A lot of people don’t know exactly what an API is. Basically, API stands for Application Programming Interface. It is, as the name says, an interface with which people — developers, users, consumers — can interact with data.

You can think of an API as a bartender. You ask the bartender for a drink, and they give you what you wanted. Simple. So why is that a problem?

Since the start of the modern web, building APIs has not been as hard as it sounds. But learning and understanding APIs was. Developers form the majority of the people that will use your API to build something or just consume data. So your API should be as clean and as intuitive as possible. A well-designed API is very easy to use and learn. It’s also intuitive, a good point to keep in mind when you’re starting to design your API.

We’ve been using REST to build APIs for a long time. Along with that comes some problems. When building an API using REST design, you’ll face some problems like:

  1. you’ll have a lot of endpoints

  2. it’ll be much harder for developers to learn and understand your API

  3. there is over- and under-fetching of information

To solve these problems, Facebook created GraphQL. Today, I think GraphQL is the best way to build APIs. This article will tell you why you should start to learn it today.

In this article, you’re going to l_earn how GraphQL work_s. I’m going to show you how to create a very well-designed, efficient, powerful API using GraphQL.

You’ve probably already heard about GraphQL, as a lot of people and companies are using it. Since GraphQL is open-source, its community has grown huge.

Now, it’s time for you start to learn in practice how GraphQL works and all about its magic.

What is GraphQL?

GraphQL is an open-source query language developed by Facebook. It provides us with a more efficient way design, create, and consume our APIs. Basically, it’s the replacement for REST.

GraphQL has a lot of features, like:

  1. You write the data that you want, and you get exactly the data that you want. No more over-fetching of information as we are used to with REST.
  2. It gives us a single endpoint, no more version 2 or version 3 for the same API.
  3. GraphQL is strongly-typed, and with that you can validate a query within the GraphQL type system before execution. It helps us build more powerful APIs.

This is a basic introduction to GraphQL — why it’s so powerful and why it’s gaining a lot of popularity these days. If you want to learn more about it, I recommend you to go the GraphQL website and check it out.

Getting started

The main objective in this article is not to learn how to set up a GraphQL server, so we’re not getting deep into that for now. The objective is to learn how GraphQL works in practice, so we’re gonna use a zero-configuration GraphQL server called ☄️ Graphpack.

To start our project, we’re going to create a new folder and you can name it whatever you want. I’m going to name it graphql-server:

Open your terminal and type:

mkdir graphql-server

Now, you should have npm or yarn installed in your machine. If you don’t know what these are, npm and yarn are package managers for the JavaScript programming language. For Node.js, the default package manager is npm.

Inside your created folder type the following command:

npm init -y 

Or if you use yarn:

yarn init 

npm will create a package.json file for you, and all the dependencies that you installed and your commands will be there.

So now, we’re going to install the only dependency that we’re going to use.

☄️Graphpack lets you create a GraphQL server with zero configuration. Since we’re just starting with GraphQL, this will help us a lot to go on and learn more without getting worried about a server configuration.

In your terminal, inside your root folder, install it like this:

npm install --save-dev graphpack 

Or, if you use yarn, you should go like this:

yarn add --dev graphpack 

After Graphpack is installed, go to our scripts in package.json file, and put the following code there:

"scripts": {
    "dev": "graphpack",
    "build": "graphpack build"
 }

We’re going to create a folder called src, and it’s going to be the only folder in our entire server.

Create a folder called src, after that, inside our folder, we’re going to create three files only.

Inside our src folder create a file called schema.graphql. Inside this first file, put the following code:

type Query {    
    hello: String    
}

In this schema.graphql file is going to be our entire GraphQL schema. If you don’t know what it is, I’ll explain later — don't worry.

Now, inside our src folder, create a second file. Call it resolvers.js and, inside this second file, put the following code:

import { users } from "./db";

const resolvers = {    
    Query: {    
        hello: () => "Hello World!"    
    }    
};

export default resolvers;

This resolvers.js file is going to be the way we provide the instructions for turning a GraphQL operation into data.

And finally, inside your src folder, create a third file. Call this db.js and, inside this third file, put the following code:

export let users = [    
    { id: 1, name: "John Doe", email: "[email protected]", age: 22 },    
    { id: 2, name: "Jane Doe", email: "[email protected]", age: 23 }    
];

In this tutorial we’re not using a real-world database. So this db.js file is going to simulate a database, just for learning purposes.

Now our src folder should look like this:

src
  |--db.js
  |--resolvers.js
  |--schema.graphql

Now, if you run the command npm run dev or, if you’re using yarn, yarn dev, you should see this output in your terminal:

You can now go to localhost:4000. This means that we’re ready to go and start writing our first queries, mutations, and subscriptions in GraphQL.

You see the GraphQL Playground, a powerful GraphQL IDE for better development workflows. If you want to learn more about GraphQL Playground, click here.

Schema

GraphQL has its own type of language that’s used to write schemas. This is a human-readable schema syntax called Schema Definition Language (SDL). The SDL will be the same, no matter what technology you’re using — you can use this with any language or framework that you want.

This schema language its very helpful because it’s simple to understand what types your API is going to have. You can understand it just by looking right it.

Types

Types are one of the most important features of GraphQL. Types are custom objects that represent how your API is going to look. For example, if you’re building a social media application, your API should have types such as Posts, Users, Likes, Groups.

Types have fields, and these fields return a specific type of data. For example, we’re going to create a User type, we should have some name, email, and age fields. Type fields can be anything, and always return a type of data as Int, Float, String, Boolean, ID, a List of Object Types, or Custom Objects Types.

So now to write our first Type, go to your schema.graphql file and replace the type Query that is already there with the following:

type User {    
    id: ID!    
    name: String!    
    email: String!    
    age: Int    
}

Each User is going to have an ID, so we gave it an ID type. User is also going to have a name and email, so we gave it a String type, and an age, which we gave an Int type. Pretty simple, right?

But, what about those ! at the end of every line? The exclamation point means that the fields are non-nullable, which means that every field must return some data in each query. The only nullable field that we’re going to have in our User type will be age.

In GraphQL, you will deal with three main concepts:

  1. queries — the way you’re going to get data from the server.
  2. mutations — the way you’re going to modify data on the server and get updated data back (create, update, delete).
  3. subscriptions — the way you’re going to maintain a real-time connection with the server.

I’m going to explain all of them to you. Let’s start with Queries.

Queries

To explain this in a simple way, queries in GraphQL are how you’re going to get data. One of the most beautiful things about queries in GraphQL is that you are just going to get the exact data that you want. No more, no less. This has a huge positive impact in our API — no more over-fetching or under-fetching information as we had with REST APIs.

We’re going to create our first type Query in GraphQL. All our queries will end up inside this type. So to start, we’ll go to our schema.graphql and write a new type called Query:

type Query {    
    users: [User!]!    
}

It’s very simple: the users query will return to us an array of one or more Users. It will not return null, because we put in the !, which means it’s a non-nullable query. It should always return something.

But we could also return a specific user. For that we’re going to create a new query called user. Inside our Query type, put the following code:

user(id: ID!): User! 

Now our Query type should look like this:

type Query {    
    users: [User!]!    
    user(id: ID!): User!    
}

As you see, with queries in GraphQL we can also pass arguments. In this case, to query for a specific user, we’re going to pass its ID.

But, you may be wondering: how does GraphQL know where get the data? That’s why we should have a resolvers.js file. That file tells GraphQL how and where it's going to fetch the data.

First, go to our resolvers.js file and import the db.js that we just created a few moments ago. Your resolvers.js file should look like this:

import { users } from "./db";

const resolvers = {    
    Query: {    
        hello: () => "Hello World!"    
    }    
};

export default resolvers;

Now, we’re going to create our first Query. Go to your resolvers.js file and replace the hello function. Now your Query type should look like this:

import { users } from "./db";

const resolvers = {    
    Query: {    
        user: (parent, { id }, context, info) => {    
        return users.find(user => user.id === id);    
        },    
        users: (parent, args, context, info) => {    
            return users;    
        }    
    }    
};

export default resolvers;

Now, to explain how is it going to work:

Each query resolver has four arguments. In the user function, we’re going to pass id as an argument, and then return the specific user that matches the passed id. Pretty simple.

In the users function, we’re just going to return the users array that already exists. It’ll always return to us all of our users.

Now, we’re going to test if our queries are working fine. Go to localhost:4000 and put in the following code:

query {    
    users {    
        id    
        name    
        email    
        age    
    }    
}

It should return to you all of our users.

Or, if you want to return a specific user:

query {    
    user(id: 1) {    
        id    
        name    
        email    
        age    
    }    
}

Now, we’re going to start learning about mutations, one of the most important features in GraphQL.

Mutations

In GraphQL, mutations are the way you’re going to modify data on the server and get updated data back. You can think like the CUD (Create, Update, Delete) of REST .

We’re going to create our first type mutation in GraphQL, and all our mutations will end up inside this type. So, to start, go to our schema.graphql and write a new type called mutation:

type Mutation {    
    createUser(id: ID!, name: String!, email: String!, age: Int): User!    
    updateUser(id: ID!, name: String, email: String, age: Int): User!    
    deleteUser(id: ID!): User!    
}

As you can see, we’re going to have three mutations:

createUser: we should pass an ID, name, email, and age. It should return a new user to us.

updateUser: we should pass an ID, and a new name, email, or age. It should return a new user to us.

deleteUser: we should pass an ID. It should return the deleted user to us.

Now, go to our resolvers.js file and below the Query object, create a new mutation object like this:

Mutation: {    
    createUser: (parent, { id, name, email, age }, context, info) => {    
        const newUser = { id, name, email, age };    
        users.push(newUser);    
        return newUser;    
},   
    updateUser: (parent, { id, name, email, age }, context, info) => {    
        let newUser = users.find(user => user.id === id);    
        newUser.name = name;    
        newUser.email = email;    
        newUser.age = age;

        return newUser;
    },    
    deleteUser: (parent, { id }, context, info) => {    
        const userIndex = users.findIndex(user => user.id === id);

        if (userIndex === -1) throw new Error("User not found.");

        const deletedUsers = users.splice(userIndex, 1);

        return deletedUsers[0];     
    }    
}

Now, our resolvers.js file should look like this:

import { users } from "./db";

const resolvers = {    
    Query: {        
        user: (parent, { id }, context, info) => {      
            return users.find(user => user.id === id);      
        },      
        users: (parent, args, context, info) => {       
            return users;       
        }       
    },    
    Mutation: {    
        createUser: (parent, { id, name, email, age }, context, info) => {    
            const newUser = { id, name, email, age };    
            users.push(newUser);    
            return newUser;    
    },   
        updateUser: (parent, { id, name, email, age }, context, info) => {    
            let newUser = users.find(user => user.id === id);    
            newUser.name = name;    
            newUser.email = email;    
            newUser.age = age;

            return newUser;
        },    
        deleteUser: (parent, { id }, context, info) => {    
            const userIndex = users.findIndex(user => user.id === id);

            if (userIndex === -1) throw new Error("User not found.");

            const deletedUsers = users.splice(userIndex, 1);

            return deletedUsers[0];         
        }    
    }    
};

export default resolvers;

Now, we’re going to test if our mutations are working fine. Go to localhost:4000 and put in the following code:

mutation {    
    createUser(id: 3, name: "Robert", email: "[email protected]", age: 21) {    
        id    
        name    
        email    
        age    
    }    
}

It should return a new user to you. If you want to try making new mutations, I recommend you to try for yourself! Try to delete this same user that you created to see if it’s working fine.

Finally, we’re going to start learning about subscriptions, and why they are so powerful.

Subscriptions

As I said before, subscriptions are the way you’re going to maintain a real-time connection with a server. That means that whenever an event occurs in the server and whenever that event is called, the server will send the corresponding data to the client.

By working with subscriptions, you can keep your app updated to the latest changes between different users.

A basic subscription is like this:

subscription {    
    users {    
        id    
        name    
        email    
        age    
    }    
}

You will say it’s very similar to a query, and yes it is. But it works differently.

When something is updated in the server, the server will run the GraphQL query specified in the subscription, and send a newly updated result to the client.

We’re not going to work with subscriptions in this specific article, but if you want to read more about them click here.

Conclusion

As you have seen, GraphQL is a new technology that is really powerful. It gives us real power to build better and well-designed APIs. That’s why I recommend you start to learn it now. For me, it will eventually replace REST.

REST vs GraphQL - What's the best kind of API?

REST vs GraphQL - What's the best kind of API?

Should you build/ use a REST API or a GraphQL API? Can you only use GraphQL with React? Time for a detailed comparison!

REST vs GraphQL - What's the best kind of API?

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading

Creating RESTful APIs with NodeJS and MongoDB Tutorial

How to build RESTful APIs with ASP.NET Core

Understanding the basics of RESTful APIs

Spring Data REST Tutorial: Developing RESTful APIs with Ease

Developing RESTful APIs with Lumen (A PHP Micro-framework)



What is REST API? – The Complete Guide to RESTful APIs

What is REST API? – The Complete Guide to RESTful APIs

We have been using different applications and web pages to get data for various resources. However, have you ever thought, where does this data come from? . So in this article on What is REST API, let us look into how a client communicates with the servers to extract the required information.

The following topics will be covered in this article "What is REST API":

  • Need of REST API
  • What is REST API?
  • Principles of REST API
  • Methods of REST API
  • How to create a REST API?

Now, before I define REST API for you, let me take you through an example to make you understand the need of REST API.

Need of REST API

Consider a scenario where you are using the Book My Show app. Now, obviously, this application needs a lot of Input data, as the data present in the application is never static. Either it is movies getting released on a frequent basis, or various cities showing different languages movies at various times of the day. It’s never static which implies to the fact that data is always changing in these applications.

Now, where do you think we get this data from?

Well, this data is received from the Server or most commonly known as a Web-server. So, the client requests the server for the required information, via an API, and then, the server sends a response to the client.

Over here, the response sent to the client is in the form of an HTML Web Page. But, do you think this is an apt response that you would expect when you send a request?

Well, I am assuming the fact that you would say NO. Since, you would prefer the data to be returned in the form of structured format, rather than the complete Web page.

So, for such reasons, the data returned by the server, in response to the request of the client is either in the format of JSON or XML. Both JSON and XML format have a proper hierarchical structure of data.

Now, this sounds quite simple, right?

But, the only issue which is present in this framework till now is that you have to use a lot of methods to get the required information. To the fact, using these methods to retrieve information, becomes quite cumbersome when you require complex data.

So, this is where REST API comes into the picture. The REST API creates an object, and thereafter send the values of an object in response to the client.

Now, that you know the need of REST, next in this article, let us look into the What is REST API?

What is REST API?

REST suggests to create an object of the data requested by the client and send the values of the object in response to the user. For example, if the user is requesting for a movie in Bangalore at a certain place and time, then you can create an object on the server side.

So, over here, you have an object and you are sending the state of an object. This is why REST is known as Representational State Transfer.

If I have to define REST, then,  Representational State Transfer a.k.a REST is an architectural style as well as an approach for communications purpose that is often used in various web services development.

The architectural style of REST helps in leveraging the lesser use of bandwidth to make an application more suitable for the internet. It is often regarded as the “language of the internet” and is completely based on the resources.

To understand better, let’s dive a little deeper and see how exactly does a REST API work. Basically, the REST API breaks down a transaction in order to create small modules. Now, each of these modules is used to address a specific part of the transaction. This approach provides more flexibility but requires a lot of effort to be built from the very scratch.

So, now that you know what is REST API, let us next understand the constraints or principles which must be satisfied for an application to be regarded as REST API.

Principles of REST API

Well, there are six ground principles laid down by Dr. Fielding who was the one to define the REST API design in 2000. Below are the six guiding principles of REST:

Stateless

The requests sent from a client to a server will contain all the required information to make the server understand the requests sent from the client. This can be either a part of URL,  query-string parameters, body, or even headers. The URL is used to uniquely identify the resource and the body holds the state of the requesting resource. Once the server processes the request, a response is sent to the client through body, status or headers

Client-Server

The client-server architecture enables a uniform interface and separates clients from the servers. This enhances the portability across multiple platforms as well as the scalability of the server components.

Uniform Interface

To obtain the uniformity throughout the application, REST has the following four interface constraints:

  • Resource identification
  • Resource Manipulation using representations
  • Self-descriptive messages
  • Hypermedia as the engine of application state

Cacheable

In order to provide a better performance, the applications are often made cacheable. This is done by labeling the response from the server as cacheable or non-cacheable either implicitly or explicitly. If the response is defined as cacheable, then the client cache can reuse the response data for equivalent responses in the future.

Layered system

The layered system architecture allows an application to be more stable by limiting component behavior. This type of architecture helps in enhancing the application’s security as components in each layer cannot interact beyond the next immediate layer they are in. Also, it enables load balancing and provides shared caches for promoting scalability.

Code on demand

This is an optional constraint and is used the least. It permits a clients code or applets to be downloaded and to be used within the application. In essence, it simplifies the clients by creating a smart application which doesn’t rely on its own code structure.

Now, that you know the principles behind REST API, next let’s look into the Methods of REST API.

Methods of REST API

All of us working with the technology of the web, do CRUD operations. When I say CRUD operations, I mean that we create a resource, read a resource, update a resource and delete a resource. Now, to do these actions, you can actually use the HTTP methods, which are nothing but the REST API Methods. Refer below.

Now that you know what is a REST API and what all you need to mind in order to deliver an efficient application, let’s dive deeper and see the process of building REST API.

How to create a REST API?

In this practical demonstration, I will be creating a simple CRUD REST application using Node.js. To build this application, you will need to install the following:

  1. Node.js
  2. Express.js
  3. Joi
  4. nodemon (Node Monitor)

For this hands-on, I will be using the WebStorm IDE to write and execute the codes. You can use any IDE or code editor according to your choice. So, let’s get started.

Step 1: Create a project directory, which will consist of all the files present in the project. Then, open commands prompt and navigate to the project directory. Refer below.

Step 2: Now, call npm using the below command. This will initialize the npm modules in your system.

npm init

Once you hit enter, Node.js, will ask you to enter a few details related to the project. These details will basically be the metadata for your project. Refer below.

Here you can define your entry point along with several other information. For this demo, I will be using script.js as an entry point.

It will then, ask you for a confirmation for the data you must have mentioned. Just press on Y to confirm. Refer below.

Step 3: Next, you have yo install Express.js using the below command:

npm i express

Express is a web framework which can be used along with Node.js. This web framework will allow you to create Restful APIs, with the help of helper methods, middle layers to configure your application.

Step 3.1: Similarly, you have to install Joi.

npm i joi

This package allows you to create blueprints for JavaScript objects which store information to ensure validation of key information.

Step 3.2: Finally, install the node monitoring package nodemon, using the below command.

npm i -g nodemon

Nodemon, keeps a watch on all the files with any type of extension present in this folder. Also, with nodemon on the watch, you don’t have to restart the Node.js server each time any changes are made. Nodemon will implicitly detect the changes and restart the server for you.

package.json

{
"name": "restapidemo",
"version": "1.0.0",
"description": "Creation of REST API",
"main": "script.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "sahiti_kappagantula",
"license": "ISC",
"dependencies": {
"express": "^4.17.1",
"joi": "^14.3.1"
}
}

script.js

const express = require('express'); //Import Express
const Joi = require('joi'); //Import Joi
const app = express(); //Create Express Application on the app variable
app.use(express.json()); //used the json file
 
//Give data to the server
const customers = [
{title: 'George', id: 1},
{title: 'Josh', id: 2},
{title: 'Tyler', id: 3},
{title: 'Alice', id: 4},
{title: 'Candice', id: 5}
]
 
//Read Request Handlers
// Display the Message when the URL consist of '/'
app.get('/', (req, res) => {
res.send('Welcome to Edurekas REST API!');
});
// Display the List Of Customers when URL consists of api customers
app.get('/api/customers', (req,res)=> {
res.send(customers);
});
// Display the Information Of Specific Customer when you mention the id.
app.get('/api/customers/:id', (req, res) => {
const customer = customers.find(c => c.id === parseInt(req.params.id));
//If there is no valid customer ID, then display an error with the following message
if (!customer) res.status(404).send('<h2 style="font-family: Malgun Gothic; color: darkred;">Ooops... Cant find what you are looking for!</h2>');
res.send(customer);
});
 
//CREATE Request Handler
//CREATE New Customer Information
app.post('/api/customers', (req, res)=> {
 
const { error } = validateCustomer(req.body);
if (error){
res.status(400).send(error.details[0].message)
return;
}
//Increment the customer id
const customer = {
id: customers.length + 1,
title: req.body.title
};
customers.push(customer);
res.send(customer);
});
 
//Update Request Handler
// Update Existing Customer Information
app.put('/api/customers/:id', (req, res) => {
const customer = customers.find(c=> c.id === parseInt(req.params.id));
if (!customer) res.status(404).send('<h2 style="font-family: Malgun Gothic; color: darkred;">Not Found!! </h2>');
 
const { error } = validateCustomer(req.body);
if (error){
res.status(400).send(error.details[0].message);
return;
}
 
customer.title = req.body.title;
res.send(customer);
});
 
//Delete Request Handler
// Delete Customer Details
app.delete('/api/customers/:id', (req, res) => {
 
const customer = customers.find( c=> c.id === parseInt(req.params.id));
if(!customer) res.status(404).send('<h2 style="font-family: Malgun Gothic; color: darkred;"> Not Found!! </h2>');
 
const index = customers.indexOf(customer);
customers.splice(index,1);
 
res.send(customer);
});
//Validate Information
function validateCustomer(customer) {
const schema = {
title: Joi.string().min(3).required()
};
return Joi.validate(customer, schema);
 
}
 
//PORT ENVIRONMENT VARIABLE
const port = process.env.PORT || 8080;
app.listen(port, () => console.log(`Listening on port ${port}..`));

Step 4: Now, the next step is to check whether the handlers are working properly or not. For that, we will use a Chrome extension called Postman. To install Postman you can visit here and click on ‘Add to Chrome’.

Step 5: Now, once you have installed Postman, open it to test your application.

Step 6: But before that you have to start your server. To start your server, type the following command.

node script.js

You would see the output as below:

Results

Let us start by testing the GET Method.

Step 7: In order to do that you need to select GET from the drop-down list, type in the defined URL and hit send.

If your code is working fine, then you will see the list of all the customers which we have added manually in our code. In the below picture, you can see how my result looks like. Here I have mentioned the URL to be localhost:8080/api/customers

Step 8: Now, let’s try adding a new customer to our stack of customers. For that, select ‘POST’ from the drop-down list and type in the defined URL for the POST method. Then, click on ‘Body’, select ‘raw’ and move on to select ‘JSON’ from the drop-down list as depicted in the below image. Now, in the text area, type in the name of your customer as shown and hit send.

If your POST method is working fine, your response body will contain the new customer’s name along with the Customer ID. Here if you observe, we have only mentioned the name but we did not give the customer ID. This implies that the Customer ID is automatically incremented

Step 9: Now, let’s try to update a Customer name. Let us say we ant to update the name of the Customer ID = 3. So, to update the data, you need to first select ‘PUT’ from the drop-down table and enter the PUT request’s URL along with the customer id you wish to update. Next in the ‘Body’, type in the new customer name and hit enter.

This will give you a response with the customer id and updated customer name.

Step 10: Finally, let’s send a ‘DELETE’ request to delete an existing record. For that select DELETE from the drop-down list and type in the URL of the delete request handler along with the customer’s details, you want to remove and hit enter. Let’s say, I want to delete the details of a customer with id = 3. If your transaction is successful, you will see the complete details of the entry you have removed in the response body.

Now, let’s send a GET request for our final list of customers.

As you can see from the above screenshot, the response body contains a total of five customers with the customer id 3 missing as we have already deleted that entry.





GraphQL vs REST: putting REST to rest

GraphQL vs REST: putting REST to rest

When you need to build an API, your mind will likely jump to REST, the de facto standard for API creation. However, this is about to change with GraphQL, as its popularity quickly rises.

When you need to build an API, your mind will likely jump to REST, the de facto standard for API creation. However, this is about to change with GraphQL, as its popularity quickly rises.

Not everyone fully understands yet what GraphQL is all about, or why it's being declared as the successor of REST, and that's exactly what I'll clear up in this article. Here I'll show off GraphQL's main features and the advantages that it has over REST, highlighting a few points in which both differ.

The goal is to provide a brief explanation to anyone who still hasn't got to know GraphQL, and clarify exactly what it does better than REST, for those who are still skeptic about this technology.

Let's start with the very basics.

What is GraphQL?

GraphQL is a query language for APIs that enables declarative data fetching in order to give the client the power to specify exactly the data that is needed from the API.

A question that I see asked a lot is:

Why was GraphQL created when we already have REST?
There are two main reasons why companies such as Facebook, Netflix and Coursera started developing alternatives to REST:

1. In the early 2010s there was a boom in mobile usage, which led to some issues with low-powered devices and sloppy networks. REST isn't optimal to deal with those problems;

2. As mobile usage increased, so did the number of different front-end frameworks and platforms that run client applications. Given REST's inflexibility, it was harder to develop a single API that could fit the requirements of every client.

If we go even further, we realize that the main reason why an alternative solution was identified was because most of the data used in modern web and mobile applications has a graph shape. For instance, newspieces have comments, and those comments may have features such as likes or spam flags, which are created or reported by users. This example describes how a graph looks like.

Consequently, Facebook started developing GraphQL. At the same time, Netflix and Coursera were also working on alternatives themselves. After Facebook open-sourced GraphQL, Coursera dropped their efforts and adopted the new tech. Netflix, however, continued developing their own REST alternative and later open sourced Falcor.

What GraphQL isn't

Now that we know what GraphQL is, I want to clarify what it is not, as I feel that there's still some confusion about it.

Firstly, it doesn't have anything to do with databases. It isn't an alternative to SQL or a brand new ORM.

Secondly, it isn't a REST replacement, but an alternative. You don't have to pick between one and the other, they can happily co-exist in the same project.

Last but not least, GraphQL isn't complicated or scary. It's quite easy to understand its declarative nature and exactly how it's possible to take the best from it.

GraphQL in context

Before moving on to the comparison with REST, I'll go through a simple GraphQL query where we can fetch a user as well as his or her name and age:

query {
  user {
    name
    age
  }
}

And the JSON response we'll get from it:

{
  "user": {
    "name": "Johnathan Joestar",
    "age": 27
   }
}

As I stated previously, GraphQL's declarative nature makes it incredibly easy to understand what's going on at all times, as we are basically writing JSON objects without the values.

Now that we have context, let's dive deep into GraphQL's features and the advantages that it has over REST.

GraphQL vs REST

In this section I'll go point by point through a practical example, comparing REST to GraphQL in order to demonstrate the flexibility of Facebook's query language.

Imagine that you have a blog, and you want the front page to show all the latest posts. In order to achieve this, you need to fetch the posts, so you will probably do something like this:

GET /api/posts

[
  {
    "title": "Cooler post",
    "subtitle": "...",
    "date": "07/05/2019"
  },
  {
    "title": "Cool post",
    "subtitle": "...",
    "date": "06/05/2019"
  }
]

But what if you want to see the author as well? You have three options to achieve this:

  • Fetch the authors from another resource:
GET /api/post/:id

{
  "post": {
    ...,
    "author": {
      "name": "Dio Brando"
    }
  }
}

  • Modify the resource to also return the author:
GET /api/posts

[
  {
    ...,
    "author": {
      "name": "Dio Brando"
    }
  },
  {
    ...,
    "author": {
      "name": "Johnathan Joestar"
    }
  }
]

  • Create a new resource that returns the posts with the author:
GET /api/postsWithAuthor

[
  {
    ...,
    "author": {
      "name": "Dio Brando"
    }
  },
  {
    ...,
    "author": {
      "name": "Johnathan Joestar"
    }
  }
]

Each of these approaches will create a problem of its own, so let's have a look at them one by one.

Under-fetching

With the first approach – fetching the authors from another resource – you'll end up with two server requests instead of one, and as you continue to scale, you may have even more requests to different endpoints in order to fetch all the needed data.

With GraphQL, this wouldn't happen. You would only have one request, and you wouldn't have to make multiple round trips to the server, as seen below:

query {
  posts {
    title
    subtitle
    date
    author {
      name
    }
  }
}

Over-fetching

Looking at the second approach – modifying the resource to also return the author – you can see that it solved the problem pretty nicely. However, changing a resource may have a secondary effect elsewhere on your application. More precisely, over-fetching.

Let's go back to your blog, but this time you also have a sidebar showing off the top monthly posts with their titles, subtitles and date, that is using the resource /api/posts. Since you modified the resource, now it also shows the author with it. However, we don't need it for the sidebar.

While this may not look like a problem, for users on limited data plans, having a website fetch useless data isn't ideal. Since GraphQL allows the client to only fetch the needed data, this problem wouldn't exist:

query {
  posts {
    title
    subtitle
    date
  }
}

Slow front-end development

Lastly, let's have a look at the last approach – creating a new resource that returns the posts with the author – since it's a common pattern to structure the endpoints according to the views in your project.

While this may solve problems such as the one described above, it also slows down the front-end development, since each specific view needs its specific endpoint. If at any point a view needs new data, the development has to slow down until the endpoint is updated.

Again, since GraphQL gives power to the client to fetch the needed data only, nothing slows down, as it's very simple to just add a new field to a query.

You would get from this:

query {
  posts {
    title
    subtitle
    date
  }
}

To this:

query {
  posts {
    title
    subtitle
    date
    author {
      name
    }
  }
}

REST vs GraphQL comparison recap

Let's just do a quick recap regarding the differences between REST and GraphQL:

  • GraphQL solves both over-fetching and under-fetching issues by allowing the client to request only the needed data;
  • Since the client now has more freedom in the fetched data, development is much faster with GraphQL than what it would be with REST.

Now we'll move on to a more in-depth overview of GraphQL's unique features.

GraphQL's features overview

Now that we know how it stacks up against REST, let's talk about some of the features that are unique to GraphQL.

Schema and Type System

GraphQL uses its own type system to define the schema of an API, with its syntax called Schema Definition Language (SDL). The schema serves as a contract between the server and the client to define how a client can access the data.

Once the schema is defined, the front-end and back-end teams can work independently, as the front-end can be easily tested with mock data. The front-end can also get useful information from the schema, such as its types, queries and mutations using GraphiQL or introspection. The schema also provides type safety, which is a plus for the front-end and back-end development, as it catches type errors early.

A schema example:

type User {
  name: String!
  age: Int
  posts: [Post!]!
}

type Post {
  title: String!
  subtitle: String!
  body: String!
  date: String!
  author: User!
}

type Query {
  users: [User!]!
  user(name: String!): User!
  posts: [Post!]!
  post(title: String!): Post!
}

type Mutation {
  createUser(name: String!, age: Int): User!
  createPost(title: String!, subtitle: String!, body: String!): Post!
}

GraphQL IDE

This is one of the most useful features of GraphQL development. A GraphQL IDE takes advantage of its self-documenting nature to make development a breeze.

Using GraphiQL or GraphQL Playground, you can just inspect your schema and even run queries and mutations to test out your API.

GraphQL Playground

Wrap up

GraphQL provides a smooth and fast development environment with its declarative and flexible nature, offering many improvements over REST. Despite being relatively new, it has already been adopted by companies such as Facebook, GitHub and many more .

It already has a large community and a vibrant ecosystem, and was already implemented in several popular languages, such as JavaScript, Go and Java.

While this post only dipped the toes into the ocean that is GraphQL, its website has a plethora of information and is an amazing place to learn and start using GraphQL.

With all this being said, it's not a perfect technology, and it still has a couple of drawbacks when compared with REST. But considering how young it is, the future looks incredibly bright for GraphQL.