Learn GraphQL in 7 minutes!

Learn GraphQL in 7 minutes!

Featured on Hashnode

Hey there! GraphQL looks like a very complex thing but it's really not the case, in fact it eases our API development process in a defined manner. In this article we're gonna learn what GraphQL is and why is it so crucial in the way we look at APIs.

So what is this "GraphQL"?

"GraphQL is for APIs as SQL is for databases." GraphQL is a new API standard that provides a more efficient, powerful and flexible alternative to REST. It sits between the front end and the backend and database. It is a query language for your APIs. It uses specific queries for creating, retrieving and manipulating data from a single endpoint, and is an alternative to the traditional RESTful API development. Let's understand by an example: Suppose we have a REST API with these endpoints:

/users
/users: id
/posts
/users:id/posts

Let's do a number of fetches:

  1. Fetch all users. No. of GET requests : 1
  2. Fetch a user with particular id. No of GET requests : 2
  3. Fetch a user with a particular id and get all posts. No of GET requests: 3

Do you see the pattern? As the API gets bigger and more complex, the number of GET or POST requests required for some simple operations gets higher, and also when we want to fetch, say a particular field inside the user, we will have to fetch the entire data as there's no way to pull out particular fields from the endpoint.

The REST APIs are just endpoints with data and have no defined way to fetch particular fields.

hero walks in hero

GraphQL is the solution! Get the data that you want, store data in a defined manner and fetch only with one endpoint. There are three main operations in GraphQL:

  • Queries, used to retrieve data
  • Mutations, used to manipulate data(creating, updating and deleting)
  • Subscriptions, used to watch events emitted from server.

Okay, now how does it work?

A basic query might look like this:

// query to get all posts
query{
    getPosts{
        id
        username
        body
    }
}


//returns a JSON response like this
{
  "data": {
    "getPosts": [
      {
        "id": "5fca4e1e6d376f1c28289c03",
        "body": "This is another post",
        "username": "Hailey",
        "createdAt": "2020-12-04T14:56:30.631Z"
      }
    ]
  }
}

Let's understand step by step:

  • We define a strongly typed Schema and we define our own types using the Schema Definition Language (SDL). If you are familiar with making Schemas in mongoDB, it's similar to that process. So if you want a type Post, you should have something like this:
type Post{
    id: ID!
    body: String!
    createdAt: String!
    username: String!
}

Also we have the three core types as well, Queries, Mutations and Subscriptions . So if you want a query which fetches all posts you will define your type Query as:

type Query{
    getPosts: [Post]
}
  • After defining a proper Schema, we define resolvers which are functions that describe how data will be stored in each field of your Schema. They basically define all the things we put in our queries, mutations and subscription types.
 Query: {
        async getPosts(){
            try{
                const posts = await Post.find();
                return posts;
            }
            catch(err){
                throw new Error(err);
            }
        }
  • After this, we just need to have a graphql server which will take our type definitions and our resolvers, bind them together and put them on our backend. We will use apollo-server for this, but there are other popular servers like express-graphql as well. Of course we need to setup our database connection too.
const server = new ApolloServer(
    {
        typeDefs,
        resolvers
    }
);

mongoose.connect(process.env.DB, { useNewUrlParser: true,useUnifiedTopology: true})
    .then( () => {
        console.log("mongoDB connected successfully!")
        return server.listen({ port: 5000 });
    })
    .then(res => {
        console.log(`Server running at ${res.url}`)
    })

Apollo Server gives us a decent looking server like this:

Apollo Server

Here, "query" is our operation, "getPosts" is a field that we have defined in our type definitions, and things like "id" and "username" are things we return for each post.

So we defined our Schema, resolvers and put them in our Apollo Server to get a minimal GraphQL API. Phew, so we have understood a lot! By now you have a proper understanding of what GraphQL actually is, why is it more powerful and a better alternative to REST, and how it actually works.

More to learn

GraphQL is an amazing new way to think about APIs and I encourage you to learn it even more, as this will definitely improve your application's performance and will give you more power over what data you fetch! Thanks for reading! If you learned something from this article, give me some unicorns and other stuff :)

 
Share this