GraphQL with Apollo Server and Express - GraphQL Series - Part 1
Tags: showdev, webdev, tutorial, beginners
Published: 2019-06-29 07:42:11

---
title: GraphQL with Apollo Server and Express - GraphQL Series - Part 1
published: true
description: GraphQL with Apollo Server and Express - GraphQL Series - Part 1
tags: showdev,webdev,tutorial,beginners
canonical_url: https://cloudnweb.dev/2019/06/graphql-with-apollo-server-and-express-graphql-series-part-1/
series: graphql
---
<!-- wp:paragraph -->
<p>In this article series, we will see how to implement GraphQL with Apollo Server and Express - GraphQL Series - Part 1</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Before going into the topic of graphql, let me ask you few questions about how web works?</p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li>How a web page in the browser(client) and server communicate?</li><li>what is stateless and stateful communication between client and server?</li><li>what is HTTP/1.1? why does it exist?</li></ul>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p>you can ask me, why do i need to know these things first. that's a good question to ask every time before you learn something new. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>If you can answer these questions, you can able to understand why we need something like GraphQL. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Let me try to make it simpler by giving you some scenarios. First of all, we all know that we use <strong>REST</strong> <strong>API</strong> for web page(client) and server(server) communication.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>REST API is nothing but an API endpoint, which gives the data when we hit a particular route.</p>
<!-- /wp:paragraph -->

<!-- wp:image {"id":817} -->
<figure class="wp-block-image"><img src="https://cloudnweb.dev/wp-content/uploads/2019/06/Untitled-Diagram-1.png" alt="" class="wp-image-817"/></figure>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>Now, you can ask me, it works fine as we expect, then what's the problem with it. Let's say that you need to get only the email address from the result of the particular API which contains the hundred's and thousand's of data.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>It is very difficult to loop the data in the web browser and display only the email address. it will affect the performance of an application.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>That's where GraphQL comes in</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>What is GraphQL ?</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>GraphQL is an alternative to REST API's. Unlike REST API's, GraphQL fetches what is only needed for the client side of the application.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Instead of returning all the data from the server, GraphQL returns only what client seeks for. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Let's say that you need email and password from the users table. GraphQL query can only fetch those details from the server.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>GraphQL provides lot of flexibility in data handling and solves the problem of loading lots of unnecessary data in the client side.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":3} -->
<h3>How GraphQL works ? </h3>
<!-- /wp:heading -->

<!-- wp:image {"id":822} -->
<figure class="wp-block-image"><img src="https://cloudnweb.dev/wp-content/uploads/2019/06/GraphQL.png" alt="" class="wp-image-822"/></figure>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p> Above all, GraphQL has only single endpoint which sends the request as query and gets the response back from the server.</p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li>client hits the <strong>/graphql</strong> endpoint with a query.</li><li>graphql sends the request details in the body of the request to the server.</li><li>the server responds to the request with a data.</li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":3} -->
<h3>GraphQL Building Blocks</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p> Mainly, there are two ways to get the data from server to client.</p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li><strong>Query </strong> - it is something similar to <strong>GET </strong>request in REST API's. with <strong>Query</strong>, we can fetch the data from the server.</li><li><strong>Mutation</strong> - mutation in GraphQL is used to update the data in the server. it is similar to <strong>POST </strong>request in the server.</li><li><strong>Subscription</strong> - it is used to handle the real-time communication between client and server using <a href="https://cloudnweb.dev/2019/06/what-are-web-sockets-implementing-web-sockets-in-node-js/">web sockets</a>. </li><li><strong>Type Definitions</strong> - Type Definitions is nothing but defining the request and response format for a particular query</li></ul>
<!-- /wp:list -->

<!-- wp:image {"id":827} -->
<figure class="wp-block-image"><img src="https://cloudnweb.dev/wp-content/uploads/2019/06/graphQL_big_picture.png" alt="" class="wp-image-827"/></figure>
<!-- /wp:image -->

<!-- wp:heading {"level":3} -->
<h3>GraphQL Query Structure</h3>
<!-- /wp:heading -->

<!-- wp:image {"id":830} -->
<figure class="wp-block-image"><img src="https://cloudnweb.dev/wp-content/uploads/2019/06/graphQL_Structure.png" alt="" class="wp-image-830"/></figure>
<!-- /wp:image -->

<!-- wp:list -->
<ul><li><strong>Operation Type</strong> - we need to define what kind of operation that we need to perform. For Example, To fetch the Data, we need to define it as a <strong>query</strong></li><li><strong>Operation Endpoint </strong> -  it defines the operation that you are going to perform whether it is a Query or Mutation</li><li><strong>Query Arguments</strong> - it is something like a query parameter. </li><li><strong>Requested Field</strong> - it defines the data that we need to fetch from the server</li></ul>
<!-- /wp:list -->

<!-- wp:heading {"level":3} -->
<h3>Implementing GraphQL</h3>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>I assume that you are familiar with Node.js and<a href="https://expressjs.com/en/starter/installing.html"> Express</a> framework. </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>create a folder and install the following dependencies</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>$ mkdir graphql-demo
$ cd graphql-demo
$ npm init --yes
$ npm install express body-parser graphql apollo-server-express</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>Mainly, <strong>graphql </strong>library is the core library package to run the graphql. <strong>apollo-server-express</strong> is used to connect the graphql and express server</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>create a file called <strong>index.js</strong> and add the following code.</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>import express from 'express'
import bodyParser  from 'body-parser';
import { ApolloServer } from 'apollo-server-express';
import typeDefs from './typedef';
import resolvers from './resolver';
const app = express();

app.use(bodyParser.json());

const server = new ApolloServer({
    introspection : true,
    typeDefs,
    resolvers,
    formatError: error => {
        return error
    },
    context : ({req,res}) => {
        return {
            req,res
        }
    }
})

server.applyMiddleware({app,path : '/graphql'})

app.listen(3030,() => {
    console.log("app is listening to port 3030");
})</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>there are two ways to configure the graphql server. one is <strong>Apollo server</strong> and another is <strong>express graphql</strong>.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>we are using <strong>apollo server</strong> to configure graphql in this tutorial.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>There are two things to notice in the <strong>index.js</strong>. they are <strong>typeDefs </strong>and <strong>resolvers</strong>.</p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li><strong>typeDefs</strong> - <strong>Type Definitions</strong> is defining the format of request and response</li><li><strong>Resolvers</strong> - <strong>Resolver </strong>is a function which handles the request and returns the data from the server.</li></ul>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p>create a file called <strong>typeDefs.js</strong> and add the following code.</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>import {gql} from 'apollo-server-express';

const typeDefs = gql`

type Author {
    id : Int!
    firstName : String
    lastName : String
    posts : [Post]
}

type Post {
    id : Int!
    title : String
    authorId : ID!
    votes :Int
}

input PostData {
    id : Int!
    title : String
    authorId : ID!
    votes :Int
}

type Response {
    success: Boolean
}

type Query {
    
    posts : [Post]
    author(id : Int!): Author
}

type Mutation {
    createPost(post : PostData) : Response
}
`
export default typeDefs;</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>you need to define <strong>Query</strong> and <strong>Mutation </strong>in the type definition. As I said before, <strong>Query </strong>and <strong>Mutation </strong>are similar to <strong>GET </strong>and <strong>POST</strong>.</p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li> <strong>Posts </strong>Query gets all the post data.  </li><li><strong>Author </strong>Query fetch all the Data for the Particular author id</li><li><strong>Create Post</strong> Mutation gets the Post data from the request and updates it in the database</li></ul>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p>create a file called in <strong>resolver.js</strong> and add the following code.</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
<pre class="wp-block-code"><code>import { find, filter } from 'lodash';

const authors = [
    { id: 1, firstName: 'Tom', lastName: 'Coleman' },
    { id: 2, firstName: 'Sashko', lastName: 'Stubailo' },
    { id: 3, firstName: 'Mikhail', lastName: 'Novikov' },
  ];
  
  const posts = [
    { id: 1, authorId: 1, title: 'Introduction to GraphQL', votes: 2 },
    { id: 2, authorId: 2, title: 'Welcome to Meteor', votes: 3 },
    { id: 3, authorId: 2, title: 'Advanced GraphQL', votes: 1 },
    { id: 4, authorId: 3, title: 'Launchpad is Cool', votes: 7 },
  ];
  

export default {

    Query : {
        posts : () => posts,
        author : (_,{ id }) => find(authors,{ id })
    },

    Mutation : {
        createPost: (_,newPost) => {
            // console.log("new post",newPost.post.id);    
            posts.push(newPost.post);
            // console.log("posts",posts);
            let result = {
                success : true
            }
           return result;
        }
    }
}</code></pre>
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>Instead of Connecting with database, we use Mock data here.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Resolver function gets the data from server and returns it as response. you need to write all the business logic here in resolvers</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Complete source code :   <a href="https://codesandbox.io/s/graphql-demo-hic8p">https://codesandbox.io/s/graphql-demo-hic8p</a> </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p> To sum up, run the command <strong>npm run start </strong>and visit the url  <strong>http://localhost:3030/graphql</strong>  in the browser. you can see something like this.</p>
<!-- /wp:paragraph -->

<!-- wp:image {"id":853} -->
<figure class="wp-block-image"><img src="https://cloudnweb.dev/wp-content/uploads/2019/06/demo_page_1-1024x459.png" alt="" class="wp-image-853"/></figure>
<!-- /wp:image -->

<!-- wp:image {"id":854} -->
<figure class="wp-block-image"><img src="https://cloudnweb.dev/wp-content/uploads/2019/06/demo_page_2-1024x714.png" alt="" class="wp-image-854"/></figure>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>That's the minimal code to run a simple graphql server.  </p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>In the upcoming Articles, GraphQL with Apollo Server and Express - GraphQL Series. we will see how to build a complete web  Application with React, Express, and GraphQL.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Until then, <strong>Happy coding</strong> :-)</p>
<!-- /wp:paragraph -->