Interact with GraphQL using Express(Node JS)
Hi developers! I hope you are with me.. I started this GraphQL article series since I felt it's an amazing query language to practice. It's really cool! So I will continue this series with a set of articles based on the experience I'm getting after trying something with this . I must say, this is still new for me and let me introduce as a newbie to GraphQL. If you haven't read my previous introduction article on GraphQL, visit the below link to read it.
Today I will try to guide you to get a hands on experience with GraphQL using Express JS. I'm sure you will like it!
Prerequisites:
Node JS and NPM should be installed in your computer. That'a all!
Let me give a brief on this practical work. Here we are just trying to integrate GraphQL into an Express JS server(Node JS). Later I will bring you more on working with complex situations with Express.
Let's start the work!
1. Setup an Express Server
We are going make a folder called gq-express. Name it as you want. Then go into the folder using terminal or cmd. We have to initiate the process to create a Node JS project in this folder. So type npm init to start it. You will prompt several questions looking for answers. You can just enter them as you want. If you are not aware of this, read the first part of this article and it will help you in this case.
As my entry point is app.js, I create a new file called app.js in the project folder. This has the server implementation.
Since we use Express, we have to install NPM module to use it. Open a terminal and type
npm install express
After installation is done, we can code to implement the server. Then app.js file will be like this..
const express = require('express');
const app = express();
const port = 4000;
app.listen(port, () => {
console.log('Server Started');
})
Now run the server by typing the command node app.js. The open web browser and type localhost:4000. You can see a console log on the terminal/cmd now. Server is up now!!! For further improvement I would like you to invite to install a npm package called nodemon. Because whenever we make changes in the Express code, we have to stop the server and restart it to track the latest changes. By installing nodemon, it will always running and tracking the chnages. It will automatically restart the server. Install using the below command.
npm install nodemon
npm install nodemon
2. Integrate GraphQL into the server
Now we have to install NPM packages to introduce GraphQL to the Express server. There are two packages to be installed. One is global package and the other one is express specified package. Let's install them using terminal.
npm install graphql express-graphql
npm install graphql express-graphql
Then we are going to require the express-graphql package with a variable. It will used as a middleware.
const graphQLHttp = require('express-graphql');
app.use('/graphql', graphQLHttp({
}));
Add this code into the server. Here we register an end point to communicate with GraphQL. That endpoint will be and go to http://localhost:4000/graphql URL. You must get and error JSON output like this..
It says that GraphQL middleware needs a schema to deal with. Schema describes the object types and relations between object types. It is the file that includes the queries to enter to the graph used in GraphQL. So we need a schema and also a scenario to make a schema based on it. So I have talked about a library scenario in the introduction article. You should refer that one. Simply imagine that we are having a library with books. Books have authors. That's all. So the graph will look like this. We send requests to get books and authors.
I will go from top to bottom.. Some comments are also there for your understanding.
First we need the global graphql package for the coding. We have to grab some items from this package. Those imported ones are GraphQLObjectType, GraphQLString, GraphQLSchema, GraphQLID. I have assigned them at the next line. GraphQLObjectType is for creating new objects and GraphQLSchema is for referring to a schema related to graphql. GraphQLString and GraphQLID are needed to define the types of attributes in objects. We can not use just String or ID here. We must import these from graphql.
Dummy data
For initial try, we need some data. Still we have not connected with a database or any other data source. That's why we need this books array. It contains 3 objects having title, category and id as its fields/attributes.
Declare first object type
In GraphQL environment, we need object types to deal with data. They are just piece of codes explaining the object structures. Since we create this for a library, I'll get the Book object type first. I have named it as BookType and created in as a GraphQLObjectType. It should have a name. Later this name will be used in relations. Then fields is a function that carrying the object attributes. There we define the types with already imported types such as GraphQLString and GraphQLID.
Define Root Query
Root query in the entering query to the graph. So, I will declare one functionality as the root query. It's fetching book by ID. First we give a name to identify it uniquely. Then we define the fields. This time it's not a function! You can see the basic structure of book here. This book word is very important! It's the word we are going to use to deal with queries. You can see it later.
book: {
type: BookType,
args: {id: {type: GraphQLString}}
}
There's a function called resolve(). This has the duty to return the needed data for a particular functionality. We use lodash to talk with data. It's a utility package available in NPM which can be used to make connections to communicate with data. No need of database models here. And we are not going to implement DB connections in this article.
return lodash.find(books, {id: args.id});
This line will tell lodash to return the book with the ID passed in as a parameter. So we have to send request in a way like this.. I will show you how to send them.
{
book(id: 1) {
id
title
category
}
}
Export module
This schema is exported to be available in the whole project with a root query. It's needed since the graph in GraphQL needs an entry point.
app.use('/graphql', graphQLHttp({
schema
}));
Now go to URL => http://localhost:4000/graphql in your browser. Did it throw an error? Look at the below error. This must be the error.
GraphQL provides an interactive UI through this pre-defined URL to deal with our back-end data. This URL needs a query string. We have to provide it. Because when we provide a query to GraphQL, it takes the query in the below format..
http://localhost:4000/graphql?query=url_encoded_query
We have set a query variable for RootQuery when we export the schema module. Look at the last code lines in schema file. So we have to setup graphiql : true to enable this querying process.
So when we enable it, this error will not be there. So another simple modification is needed for graphql endpoint. Grab the below code and replace!
app.use('/graphql', graphQLHttp({
schema,
graphiql: true
}));
So final version of our Express server is included in the following gist. Get it!
Now again go to the URL => http://localhost:4000/graphql
What is the output? An interface like this?
So guys, this is the UI provided by GraphQL to communicate with data. It can send requests to our server and get responses. I'll present a simple demo on this.
Let's try one query! The below image includes the request to fetch the book with ID 1.
The response will be..
I have mentioned in my introduction, in GraphQL we can declare the data attributes we want. So, there's no waste. It leads to performance improvements since it does not go for all the attributes in each object. It just take the values we define. If you don't want id, you can remove it. Send the below request also.
{
book(id: 1) {
title
}
}
Response should be like this... It returns the data belongs to the fields we define..
This is the end of the article guys! I have just started trying GraphQL with Express JS.. I will update more on this topic in future. Next article will be based on more object types and relations with GraphQL according to this library scenario,most probably.
Till then, good bye guys!
app.use('/graphql', graphQLHttp({
}));
Add this code into the server. Here we register an end point to communicate with GraphQL. That endpoint will be and go to http://localhost:4000/graphql URL. You must get and error JSON output like this..
It says that GraphQL middleware needs a schema to deal with. Schema describes the object types and relations between object types. It is the file that includes the queries to enter to the graph used in GraphQL. So we need a schema and also a scenario to make a schema based on it. So I have talked about a library scenario in the introduction article. You should refer that one. Simply imagine that we are having a library with books. Books have authors. That's all. So the graph will look like this. We send requests to get books and authors.
3. Create a schema for the scenario
Now create a new folder called schema or any other name and create a file called schema.js. First grab the code in the following GIST and let me explain it next.I will go from top to bottom.. Some comments are also there for your understanding.
First we need the global graphql package for the coding. We have to grab some items from this package. Those imported ones are GraphQLObjectType, GraphQLString, GraphQLSchema, GraphQLID. I have assigned them at the next line. GraphQLObjectType is for creating new objects and GraphQLSchema is for referring to a schema related to graphql. GraphQLString and GraphQLID are needed to define the types of attributes in objects. We can not use just String or ID here. We must import these from graphql.
Dummy data
For initial try, we need some data. Still we have not connected with a database or any other data source. That's why we need this books array. It contains 3 objects having title, category and id as its fields/attributes.
Declare first object type
In GraphQL environment, we need object types to deal with data. They are just piece of codes explaining the object structures. Since we create this for a library, I'll get the Book object type first. I have named it as BookType and created in as a GraphQLObjectType. It should have a name. Later this name will be used in relations. Then fields is a function that carrying the object attributes. There we define the types with already imported types such as GraphQLString and GraphQLID.
Define Root Query
Root query in the entering query to the graph. So, I will declare one functionality as the root query. It's fetching book by ID. First we give a name to identify it uniquely. Then we define the fields. This time it's not a function! You can see the basic structure of book here. This book word is very important! It's the word we are going to use to deal with queries. You can see it later.
book: {
type: BookType,
args: {id: {type: GraphQLString}}
}
There's a function called resolve(). This has the duty to return the needed data for a particular functionality. We use lodash to talk with data. It's a utility package available in NPM which can be used to make connections to communicate with data. No need of database models here. And we are not going to implement DB connections in this article.
return lodash.find(books, {id: args.id});
This line will tell lodash to return the book with the ID passed in as a parameter. So we have to send request in a way like this.. I will show you how to send them.
{
book(id: 1) {
id
title
category
}
}
Export module
This schema is exported to be available in the whole project with a root query. It's needed since the graph in GraphQL needs an entry point.
4. Modify GraphQL endpoint
Now our schema is ready! Go to app.js again and modify the endpoint like this.app.use('/graphql', graphQLHttp({
schema
}));
Now go to URL => http://localhost:4000/graphql in your browser. Did it throw an error? Look at the below error. This must be the error.
GraphQL provides an interactive UI through this pre-defined URL to deal with our back-end data. This URL needs a query string. We have to provide it. Because when we provide a query to GraphQL, it takes the query in the below format..
http://localhost:4000/graphql?query=url_encoded_query
We have set a query variable for RootQuery when we export the schema module. Look at the last code lines in schema file. So we have to setup graphiql : true to enable this querying process.
So when we enable it, this error will not be there. So another simple modification is needed for graphql endpoint. Grab the below code and replace!
app.use('/graphql', graphQLHttp({
schema,
graphiql: true
}));
So final version of our Express server is included in the following gist. Get it!
Now again go to the URL => http://localhost:4000/graphql
What is the output? An interface like this?
So guys, this is the UI provided by GraphQL to communicate with data. It can send requests to our server and get responses. I'll present a simple demo on this.
5. Test the queries with GraphQL
For now, we are going to send a request to fetch a book from our data array. There's a defined way to send a request. The words will be suggested automatically what should be used, when you type on the left panel. I told that book word will be important. Here we must use it to fetch a book by ID.Let's try one query! The below image includes the request to fetch the book with ID 1.
The response will be..
I have mentioned in my introduction, in GraphQL we can declare the data attributes we want. So, there's no waste. It leads to performance improvements since it does not go for all the attributes in each object. It just take the values we define. If you don't want id, you can remove it. Send the below request also.
{
book(id: 1) {
title
}
}
Response should be like this... It returns the data belongs to the fields we define..
This is the end of the article guys! I have just started trying GraphQL with Express JS.. I will update more on this topic in future. Next article will be based on more object types and relations with GraphQL according to this library scenario,most probably.
Till then, good bye guys!
24 Comments
sebab banyak orang ingin memainkan poker online namun belum memiliki rekening di bank. Bila kamu salah satu diantaranya
ReplyDeleteasikqq
dewaqq
sumoqq
interqq
pionpoker
bandar ceme terbaik
hobiqq
paito warna
bocoran sgp
data hk
This comment has been removed by the author.
ReplyDeleteI am very grateful to read your blog.I hope you would provide the great services in the field. Web Development Company in Bangalore | Website Design Companies in Bangalore | Web Design Companies in Bangalore
ReplyDeletethank you very much for your feedback :D
DeleteThanks for sharing such an awesome blog.
ReplyDeleteNode JS Online training
Node JS training in Hyderabad
Thank Full Stack :D
DeleteAs stated by Stanford Medical, It's in fact the one and ONLY reason this country's women live 10 years more and weigh an average of 19 kilos less than we do.
ReplyDelete(By the way, it has absoloutely NOTHING to do with genetics or some secret-exercise and absolutely EVERYTHING to around "how" they eat.)
P.S, I said "HOW", and not "WHAT"...
Click on this link to uncover if this brief questionnaire can help you find out your real weight loss possibility
Thank you :D
ReplyDeletethanks
ReplyDeleteNicely Described! To support the demand for node.js app development, I would also like to share that, 43% of Node JS devs use it for enterprise applications and 85% use it primarily for web app development in 2022. Constantly, node.js development companies are rising rapidly with the increasing demand of node.js development services.
ReplyDeleteWplentioAprimda Jennifer Williams https://wakelet.com/wake/YmGMQzrsc6uossHg_isP6
ReplyDeleteconmathatu
To add GraphQL to the Express server, we must now instal NPM packages. Installing two packages is required. One is a general package, and the other is an expressly designated package. Using the terminal, let's instal them.Carlos Julio Heydra Castillo
ReplyDeleteSAP Business One ERP software is the one stop solution for the small business and organization.With this, organizations can streamline, organize, and digitize their entire operations.Therefore, this ERP connects and streamlines all business processes, enabling profitable growth.
ReplyDelete
ReplyDeleteHi, as for providing this information is very informative.
Laiqa Heavy Flow Pads|soft sanitary pads
Integrate GraphQL into an Express JS server(Node JS). This is ehat i was searching for thank dor sharing this with us
ReplyDeleteGet top-notch Law assignment help from qualified experts. We offer personalized support to enhance your understanding and improve your grades in legal coursework.
ReplyDeleteJersy espresso cups offer a smooth and strong arrangement, ideal for participating in your main mix in a rush. Made with superb materials, they join style and ability for an excellent espresso experience. Coffee Cups
ReplyDeleteWelcome to 1xbet – your trusted gateway to 1xBet’s world of gaming and entertainment. We provide a seamless, secure login experience for users to access live sports, casino games, and global events with ease.
ReplyDeleteT10 Exchange offers seamless online gaming and sports exchange experiences. With a user-friendly interface, diverse game options, secure transactions, and 24/7 customer support, it’s the go-to platform for enthusiasts. Explore innovative features and join a trusted community to enhance your gaming journey.
ReplyDeleteSatsport is your ultimate destination for cutting-edge sports insights and services in India. Offering a seamless platform for sports enthusiasts, we specialize in delivering real-time updates, secure transactions, and an unmatched user experience. Discover the best of sports engagement with Satsports today!"
ReplyDeleteFINTECHZOOM provides the latest news about Financial Markets, Stocks, Dow Jones, Nasdaq, Commodities, Loans, Mortgages, Crypto and Banking How much money i spent on league
ReplyDeleteLift your style with the varsity coat men combination by Brand Name Drip Infinity, blending imperishable arrangement in with current intricacy. varsity jacket men
ReplyDeleteLift your style with the ever-enduring charm of Drip Infinity varsity coat for men, blending praiseworthy arrangement in with current intricacy. varsity jacket for men
ReplyDeleteI have been searching all over the internet for this piece of information. Thank you for sharing Business Vocabulary in Use PDF | How to Improve Your English Skills | Conversational English Classes | Business English Expressions PDF | Improve Your Spoken English Skills | English for Meetings PDF | Business Communication Words and Phrases | Professional Vocabulary | Expand Corporate Vocabulary | Best Business English Certifications
ReplyDelete