GraphQL with Apollo Server and Express - GraphQL Series - Part 1

In this article series, we will see how to implement GraphQL with Apollo Server and Express - GraphQL Series - Part 1

Before going into the topic of graphql, let me ask you few questions about how web works?

  • How a web page in the browser(client) and server communicate?
  • what is stateless and stateful communication between client and server?
  • what is HTTP/1.1? why does it exist?

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.

If you can answer these questions, you can able to understand why we need something like GraphQL.

Let me try to make it simpler by giving you some scenarios. First of all, we all know that we use REST API for web page(client) and server(server) communication.

REST API is nothing but an API endpoint, which gives the data when we hit a particular route.

Untitled Diagram 1

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.

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.

That's where GraphQL comes in

What is GraphQL ?

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.

Instead of returning all the data from the server, GraphQL returns only what client seeks for.

Let's say that you need email and password from the users table. GraphQL query can only fetch those details from the server.

GraphQL provides lot of flexibility in data handling and solves the problem of loading lots of unnecessary data in the client side.

How GraphQL works ?

GraphQL

Above all, GraphQL has only single endpoint which sends the request as query and gets the response back from the server.

  • client hits the /graphql endpoint with a query.
  • graphql sends the request details in the body of the request to the server.
  • the server responds to the request with a data.

GraphQL Building Blocks

Mainly, there are two ways to get the data from server to client.

  • Query - it is something similar to GET request in REST API's. with Query, we can fetch the data from the server.
  • Mutation - mutation in GraphQL is used to update the data in the server. it is similar to POST request in the server.
  • Subscription - it is used to handle the real-time communication between client and server using web sockets.
  • Type Definitions - Type Definitions is nothing but defining the request and response format for a particular query

graphQL big picture

GraphQL Query Structure

graphQL Structure

  • Operation Type - 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 query
  • Operation Endpoint - it defines the operation that you are going to perform whether it is a Query or Mutation
  • Query Arguments - it is something like a query parameter.
  • Requested Field - it defines the data that we need to fetch from the server

Implementing GraphQL

I assume that you are familiar with Node.js and Express framework.

create a folder and install the following dependencies

1$ mkdir graphql-demo
2$ cd graphql-demo
3$ npm init --yes
4$ npm install express body-parser graphql apollo-server-express

Mainly, graphql library is the core library package to run the graphql. apollo-server-express is used to connect the graphql and express server

create a file called index.js and add the following code.

1import express from "express"
2import bodyParser from "body-parser"
3import { ApolloServer } from "apollo-server-express"
4import typeDefs from "./typedef"
5import resolvers from "./resolver"
6const app = express()
7
8app.use(bodyParser.json())
9
10const server = new ApolloServer({
11 introspection: true,
12 typeDefs,
13 resolvers,
14 formatError: error => {
15 return error
16 },
17 context: ({ req, res }) => {
18 return {
19 req,
20 res,
21 }
22 },
23})
24
25server.applyMiddleware({ app, path: "/graphql" })
26
27app.listen(3030, () => {
28 console.log("app is listening to port 3030")
29})

there are two ways to configure the graphql server. one is Apollo server and another is express graphql.

we are using apollo server to configure graphql in this tutorial.

There are two things to notice in the index.js. they are typeDefs and resolvers.

  • typeDefs - Type Definitions is defining the format of request and response
  • Resolvers - Resolver is a function which handles the request and returns the data from the server.

create a file called typeDefs.js and add the following code.

1import { gql } from "apollo-server-express"
2
3const typeDefs = gql`
4 type Author {
5 id: Int!
6 firstName: String
7 lastName: String
8 posts: [Post]
9 }
10
11 type Post {
12 id: Int!
13 title: String
14 authorId: ID!
15 votes: Int
16 }
17
18 input PostData {
19 id: Int!
20 title: String
21 authorId: ID!
22 votes: Int
23 }
24
25 type Response {
26 success: Boolean
27 }
28
29 type Query {
30 posts: [Post]
31 author(id: Int!): Author
32 }
33
34 type Mutation {
35 createPost(post: PostData): Response
36 }
37`
38export default typeDefs

you need to define Query and Mutation in the type definition. As I said before, Query and Mutation are similar to GET and POST.

  • Posts Query gets all the post data.
  • Author Query fetch all the Data for the Particular author id
  • Create Post Mutation gets the Post data from the request and updates it in the database

create a file called in resolver.js and add the following code.

1import { find, filter } from "lodash"
2
3const authors = [
4 { id: 1, firstName: "Tom", lastName: "Coleman" },
5 { id: 2, firstName: "Sashko", lastName: "Stubailo" },
6 { id: 3, firstName: "Mikhail", lastName: "Novikov" },
7]
8
9const posts = [
10 { id: 1, authorId: 1, title: "Introduction to GraphQL", votes: 2 },
11 { id: 2, authorId: 2, title: "Welcome to Meteor", votes: 3 },
12 { id: 3, authorId: 2, title: "Advanced GraphQL", votes: 1 },
13 { id: 4, authorId: 3, title: "Launchpad is Cool", votes: 7 },
14]
15
16export default {
17 Query: {
18 posts: () => posts,
19 author: (_, { id }) => find(authors, { id }),
20 },
21
22 Mutation: {
23 createPost: (_, newPost) => {
24 // console.log("new post",newPost.post.id);
25 posts.push(newPost.post)
26 // console.log("posts",posts);
27 let result = {
28 success: true,
29 }
30 return result
31 },
32 },
33}

Instead of Connecting with database, we use Mock data here.

Resolver function gets the data from server and returns it as response. you need to write all the business logic here in resolvers

Complete source code : https://codesandbox.io/s/graphql-demo-hic8p

To sum up, run the command npm run start and visit the url http://localhost:3030/graphql in the browser. you can see something like this.

demo page 1

demo page 2

That's the minimal code to run a simple graphql server.

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.

Until then, Happy coding :-)

To Read More

Kubernetes for Nodejs developers

Do you keep hearing the word kubernetes in the tech community and you couldn't u...

TypeScript Interfaces vs Types

In this article, we will see what are interfaces and types and the difference be...

How to find project ideas to practi...

Ever wondered what how to get a real world experience on web development while w...

Building a Production-grade Nodejs,...

This article is the first part of building a production grade nodejs,graphql and...

Modern React Redux Tutorials with R...

This tutorial explain how you can build an application using modern react redux ...

Building a Piano with React Hooks

In this article, we will see how to build a piano with react hooks. Building a P...

TypeScript Basics - The Definitive ...

In this article, we will learn some basics of typescript which helps you to deve...

Here's why podman is more secured t...

In this article we will see about podman and why it is more secured way to run c...

What is gRPC ? How to implement gRP...

Everyone talks about gRPC. Have you ever wonder how it works or how to implement...