DEV Community

Altoneisha Rose
Altoneisha Rose

Posted on

An Introduction to GraphQL

Introduction

We have been using REST architecture to build APIs. This structure is still very well used but it also has it's issues. REST comes with some problems such as: Having to use multiple urls and over fetching data. There needs to be a solution for us getting the exact data that we want instead of a huge object of items that will not get touched by us.This is where GraphQL comes into play.

What is GraphQL

GraphQL is an open-source query language developed by Facebook.
GraphQL structures data in the form of a graph with its powerful query syntax. Because of the data being structured like a graph we can sort through the data as we would a graph by: traversing, retrieving, and modifying data. It provides us with a more efficient way to design, create, and consume our APIs. On the backend, what GraphQL does is essentially creates a middleman service to filter what we get from an api. By doing this it avoids Over-fetching of data and the use of multiple urls.

Getting Started with GraphQL

To work, GraphQL needs a server and a client. Let's talk about the server. we can attach graphQL to a node server or any other type of server. When this is attached we essentially create a node/graphql server or express/graphql server. Now let's do this using express. The first thing to do is create a basic express server. Next, we need to create an express graphql server. This
require a plugin called express-graphql that creates a /graphql endpoint.

Setting up the server

const express = require('express')
const app = express()
const { graphqlHTTP } = require('express-graphql')

var schema = buildSchema(`
  type Query {
    welcome: String
  }
`);
// root gives us a resolver
var root = {
  welcome: () => {
    return 'Welcome to the GraphQL World!';
  },
};
app.use('/graphql', graphqlHTTP( req => {
  return {
   schema: schema,
   rootValue: root,
   graphiql: true,
  }
}))
app.listen(3000)
console.log('Listening')

Makes fetching data more efficient

Sending a request to an api can give us back more data then we need. GraphQL allows us to send a query to the api to get back what we want. It restricts data that should be fetched from the server. Let's look at an example of a query to fetch data

Fetch data example

// basic query
{
   students {
      id
      firstName
   }
}

// Result of the query

{
   "data": {
      "students": [
         {
            "id": "1",
            "firstName": "Paula"
         },
         {
            "id": "2",
            "firstName": "Greg"
         },
         {
            "id": "3",
            "firstName": "Stephanie"
         }
      ]
   }
}

Avoids using multiple urls

GraphQL Can query multiple relational data in a single request. Which decreases the need for multiple urls/endpoints. By doing this GraphQL utilizes selective endpoints.
Let’s look at an example

Who needs multiple urls? Example

// multiple url query
{
   student(id: "10"){
      firstName
      lastName
      college{
         name
         location
      }
   }
}

/// result
{
   "data": {
      "students": [
         {
            "firstName": "Max",
            "lastName": "Kelly",
            "college": {
               "name": " University",
               "location": "Alabama"
              }
         },
   }
}

Normally we would need to send a request to multiple urls but with GraphQL we can do this with just one request.

Schema Example

type Query {
  Students[Students!]!
}

type Mutation {
  createStudent(collegeId:ID,firstName:String,lastName:String):String 
  updateStudent(collegeId:ID,firstName:String,lastName:String): Student!    
  deleteStudent(collegeId: ID!): Student!   
}

type Student {
   id:ID!
   firstName:String!
   lastName:String!
   college:College
}

type College {
   id:ID!
   name:String!
   location:String
   students:[Student]
}

In this schema we set up how our data will look when we request it. We also set up an optional mutation that we can implement to manipulate the data.

Mutations

Mutations are optional in queries. They are equivalent to CRUD applications in REST. Mutations are how we will modify the data on the server and get updated data back. With these mutations we can: Create, Update, and Delete data entries.

Conclusion

In conclusion, GraphQL makes it easier for us to be selective on the data we receive back from external API’s. GraphQL is language agnostic which makes it easy to incorporate in any type of language. GraphQL can use some of these same techniques and schema to interact with databases. It pairs well with both document and relational database even though it types seems more geared towards document databases

Discussion (2)

Collapse
nickgarfield profile image
Nicholas Garfield

This is a great intro to GraphQL! I've recently been exploring Hasura which makes it super easy to quickly spin up a database and basic GraphQL API. Would recommend trying it out if you're setting up a new GraphQL project

Collapse
neisha1618 profile image
Altoneisha Rose Author

Will do, thank you