How to Build a GraphQL server with NodeJS and Express
Last Updated :
16 Dec, 2023
GraphQL is the open-supply question-based language that is used for querying the data. The main task of GraphQL is to execute the given question return the appropriate facts and represent it to the person. GrapghQL is the advancement of conventional REST API architecture presenting greater features. In this newsletter, we are able to see the ste[s to create the Simple GraphQL server. We can even execute the query and based on that query the result might be fetched.
Prerequisites:
Steps to create a GraphQL Server with Node & Express
Step 1: Create a New Directory by running the following command on vs code.
mkdir simple-graphql-server
cd simple-graphql-server
Step 2: Initialize the Project using the following command.
npm init -y
Step 3: Install the required dependencies for the project
npm install express express-graphql graphql
Folder Structure:
Folder Structure
The updated dependencies in package.json file will look like:
"dependencies": {
"express": "^4.18.2",
"express-graphql": "^0.12.0",
"graphql": "^15.8.0"
}
Example: Create GraphQL schema in schema.js file and setup it in app.js file.
Javascript
const { GraphQLObjectType, GraphQLString, GraphQLSchema } = require( 'graphql' );
const ArticleType = new GraphQLObjectType({
name: 'Article' ,
fields: {
id: { type: GraphQLString },
title: { type: GraphQLString },
content: { type: GraphQLString },
},
});
const RootQuery = new GraphQLObjectType({
name: 'RootQueryType' ,
fields: {
article: {
type: ArticleType,
args: { id: { type: GraphQLString } },
resolve(parent, args) {
const articleData = {
id: args.id,
title: 'Introduction to GraphQL' ,
content: 'This is a sample article about GraphQL on GeeksforGeeks.' ,
};
return articleData;
},
},
},
});
module.exports = new GraphQLSchema({
query: RootQuery,
});
|
Javascript
const express = require( 'express' );
const { graphqlHTTP } = require( 'express-graphql' );
const schema = require( './schema' );
const app = express();
app.use(
'/graphql' ,
graphqlHTTP({
schema: schema,
graphiql: true ,
})
);
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
|
Step to run the application: Run the Server using the following command.
node server.js
Output:
How to test GraphQL Server?
To test the server we will try the following query in the GraphiQL interface
query {
article(id: "1") {
id
title
content
}
}
This query has fetched the details for us which are specified in the schema.
Output:
\
Share your thoughts in the comments
Please Login to comment...