Welcome folks today in this blog post we will be building a graphql api server in node.js and express and also consume it at the frontend using html5 and javascript. All the full source code of the application is shown below.
Get Started
In order to get started you need to create a new node.js project by typing the below command as shown below
npm init -y
This will create the package.json file inside your node.js project. And now you need to install the below dependencies inside your project as shown below
npm i express
npm i cors
npm i --save-dev nodemon
Now we are installing the express library for making the web server and also installing cors package to allow the api to consumed from the frontend. And also lastly we need to install the nodemon dependency to restart the server when we make any kind of changes.
npm i graphql@14
npm i express-graphql
npm i @graphql-tools/schema
And also we are installing the graphql library and also we are installing the express-graphql package specifically for using it in express server. And also we are installing the graphql tools and schema library.
Now we need to create a record inside package.json file to use import statement inside index.js file.
package.json
1 |
"type": "module", |
We have to add this type
parameter and we need to set it to module.
Now we need to install the index.js
file and copy paste the below code.
index.js
1 2 3 4 5 6 7 8 |
import express from 'express' const app = express() const port = 4000 app.listen(port, () => { console.log(`Running a server at http://localhost:${port}`) }) |
Now we are initializing an express
server and starting it at port 4000.
Including the Middlewares for this app
1 2 3 4 5 6 |
import express from 'express' import cors from 'cors' app.use(cors()) app.use(express.json()) app.use(express.urlencoded({ extended: true })) |
Now in this block of code we are including the cors middleware so that this api can be consumed from different origins. And also applying express.json() and express.urlencoded() middlewares for forms.
Including the GraphQL Server in Express
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
import { graphqlHTTP } from 'express-graphql' import { makeExecutableSchema } from '@graphql-tools/schema' // In-memory data store const data = { warriors: [ { id: '001', name: 'Jaime' }, { id: '002', name: 'Jorah' }, {name:"John"} ], } // Schema const typeDefs = ` type Warrior { id: ID! name: String! } type Query { warriors: [Warrior] } ` // Resolver for warriors const resolvers = { Query: { warriors: (obj, args, context) => context.warriors, }, } const executableSchema = makeExecutableSchema({ typeDefs, resolvers, }) // Entrypoint app.use( '/graphql', graphqlHTTP({ schema: executableSchema, context: data, graphiql: true, }) ) |
Now inside this block of code we are including the graphql library at the top. And also we are making the static data array which contains multiple objects having two fields id and name both are required. We have defined the schema. And then we are passing this middleware of graphql to a new endpoint /graphql
where we are passing the three parameters which is schema,context and graphiql.
Now if we run the node.js app inside the terminal by typing the below command as shown below
nodemon index.js
As you can see if we open localhost:4000/graphql
we will see the following graphql interface and then we can query the api passing the below parameters which is name and id. This is a great advantage graphql offers we can only request only the parameters and data which we need.
Wrapping it up The full index.js
source code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
import express from 'express' import cors from 'cors' import { graphqlHTTP } from 'express-graphql' import { makeExecutableSchema } from '@graphql-tools/schema' const app = express() const port = 4000 // In-memory data store const data = { warriors: [ { id: '001', name: 'Jaime' }, { id: '002', name: 'Jorah' }, {name:"John"} ], } // Schema const typeDefs = ` type Warrior { id: ID! name: String! } type Query { warriors: [Warrior] } ` // Resolver for warriors const resolvers = { Query: { warriors: (obj, args, context) => context.warriors, }, } const executableSchema = makeExecutableSchema({ typeDefs, resolvers, }) app.use(cors()) app.use(express.json()) app.use(express.urlencoded({ extended: true })) // Entrypoint app.use( '/graphql', graphqlHTTP({ schema: executableSchema, context: data, graphiql: true, }) ) app.listen(port, () => { console.log(`Running a server at http://localhost:${port}`) }) |
Consuming the GraphQL API in Browser
Now we will be consuming the graphql api inside browser. For this we need to make an index.html
file and copy paste the following code
index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>GraphQL</title> </head> <pre></pre> <p id="result"></p> <body> <script> async function queryGraphQLServer() { const response = await fetch('http://localhost:4000/graphql', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ query: '{ warriors { name } }', }), }) const result = await response.json() console.log(result) result.data.warriors.forEach(warrior => { let span = document.createElement('span') span.innerHTML = "The name is " + warrior.name + "<br><br>" document.getElementById('result').appendChild(span) }); const pre = document.querySelector('pre') pre.textContent = JSON.stringify(result, null, 2) // Pretty-print the JSON } queryGraphQLServer() </script> </body> </html> |
Now inside this html file we are consuming this graphql api using the fetch api and then we are getting the response and fetching the name and id and displaying it inside the browser. It is so easy when it comes to graphql to build api and consuming it on the frontend.