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?
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.
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
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.
Above all, GraphQL has only single endpoint which sends the request as query and gets the response back from the server.
Mainly, there are two ways to get the data from server to client.
I assume that you are familiar with Node.js and Express framework.
create a folder and install the following dependencies
1$ mkdir graphql-demo2$ cd graphql-demo3$ npm init --yes4$ 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()78app.use(bodyParser.json())910const server = new ApolloServer({11 introspection: true,12 typeDefs,13 resolvers,14 formatError: error => {15 return error16 },17 context: ({ req, res }) => {18 return {19 req,20 res,21 }22 },23})2425server.applyMiddleware({ app, path: "/graphql" })2627app.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.
create a file called typeDefs.js and add the following code.
1import { gql } from "apollo-server-express"23const typeDefs = gql`4 type Author {5 id: Int!6 firstName: String7 lastName: String8 posts: [Post]9 }1011 type Post {12 id: Int!13 title: String14 authorId: ID!15 votes: Int16 }1718 input PostData {19 id: Int!20 title: String21 authorId: ID!22 votes: Int23 }2425 type Response {26 success: Boolean27 }2829 type Query {30 posts: [Post]31 author(id: Int!): Author32 }3334 type Mutation {35 createPost(post: PostData): Response36 }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.
create a file called in resolver.js and add the following code.
1import { find, filter } from "lodash"23const authors = [4 { id: 1, firstName: "Tom", lastName: "Coleman" },5 { id: 2, firstName: "Sashko", lastName: "Stubailo" },6 { id: 3, firstName: "Mikhail", lastName: "Novikov" },7]89const 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]1516export default {17 Query: {18 posts: () => posts,19 author: (_, { id }) => find(authors, { id }),20 },2122 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 result31 },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.
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 :-)
No spam, ever. Unsubscribe anytime.