Kick start graphQL

What is GraphQL

GraphQL is query language which is designed to operate over a single end point via HTTP with optimize for performance and flexibility.

Why we need GraphQL

Actually, it helps to address some of the more common headaches which is faced by developers when building a REST API  in Backend application.

Suppose we need develop a api which will return news feed. So we define the end point /posts?limit=20

Response will be

  "posts": [
      "id": "01",
      "title": "Hello Title",
      "author": "11",
      "content": "Hello content"

Now we need to amend the api to get author’s name and avatar URL

  • Define the query type
// Construct a schema, using GraphQL language
var schema = buildSchema(`
  type Query {
    hello: String
  • Need a API root with a function called a “Resolver” for each API endpoint
// The root provides a resolver function for each API endpoint
var root = {
  hello: () => {
    return 'Hello world!';


// Run the GraphQl query '{ hello }' and print out the response

graphql(schema, '{ hello }', root).then((respnse) => {


For creating server

  • express
  • express-graphql
var express = require('express');
var graphqlHTTP = require('express-graphql');
var {buildSchema} = require('graphql');


// create the server for endpoint

var app = express();
app.use('/graphql', graphqlHTTP({
  schema: schema,
  rootValue: root,
  graphiql: true
console.log('Running the GraphQL server at the localhost:4000/graphql');


How to use in client

fetch('/graphql', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json',
  body: JSON.stringify({query: "{ hello }"})
  .then(r => r.json())
  .then(data => console.log('data returned:', data));



You May Also Like

About the Author: Md. Delwar Hossain

He has 11 years of experience in developing standalone software and web applications for multiple database platforms. He has been passionate about new tools and technologies. He is positive and trustworthy. He is capable to learn and adapt quickly to different situations. He is a great team player and enjoys leading and mentoring. He is specialized in architecting and building complex web and mobile application. He has strong skills to automate POS, inventory, supply chain, trading export/ import, human resource management, manufacturing and production, distribution management system and hospital management system.

Leave a Reply

Your email address will not be published. Required fields are marked *