To gather information from the REST API designed app you need to send requests to multiple REST endpoints. So this kind of approach is scattered across multiple endpoints. GraphQL solves these obvious flaws and instead of sending requests through multiple endpoints, it has only one endpoint where you can gather data from multiple collections. In this tutorial, I will explain how to setup GraphQL
with Node.js on Debian-based distro.
Prerequisites
- Debian 11
- Node.js installed on Debian.
Setup GraphQL environment
Step 1. Navigate the project directory path and, run:
npm init
Step 2. Install GraphQL
.
npm install graphql --save
Create basic GraphQL API to handle queries
Put the following code into the server.js
file:
var { graphql, buildSchema } = require('graphql');
var schema = buildSchema(`
type Query {
hellographql: String
}
`);
var root = {
hellographql: () => {
return 'Hello GraphQL!!!';
},
};
graphql(schema, '{ hellographql }', root).then((response) => {
console.log(response);
});
Once you are done, run the API with:
node server.js
The output should be:
{ data: { hello: 'Hello GraphQL!!!' } }
Conclusion
If you work on more complex GraphQL scenarios you will have to run GraphQL queries from an API server instead of using CLI. Feel free to leave a comment below and if you find this tutorial useful, follow our official channel on Telegram.