Super Simple GraphQL with Node

john sunam
Devnetwork
6 min readJul 30, 2019

--

In this blog, I will be giving you a small introduction on GraphQL and create a simple GraphQL API using Node.js.

GraphQL is a new API standard that was invented and open-sourced by Facebook. It enables declarative data fetching where a client can specify exactly what data it needs from an API. Instead of multiple endpoints with fixed data structures, GraphQL server exposes a single endpoint and responds with data that client asked for.

This is how the REST API works.

This is how GraphQL replaces it.

Let’s create GraphQL API with Node.js and Express.js.

Setting up the project

Let us create the project folder :

$ mkdir graphql-server

Go inside the newly created project folder and initiate package.json file

$ cd graphql-server
$ npm init

We need to add some of the NPM packages for setting up the GraphQL Node.js server.

$ npm install graphql express express-graphql —-save

After installing these packages we are now ready to create GraphQL server. Let's create server.js file where we will be writing code to implement GraphQL Node.js server.

$ touch server.js

Setting up simple GraphQL server with Express

Let's write some code in server.js file for setting up GraphQL server.

const express = require('express');
const graphqlHttp = require('express-graphql');
const { buildSchema } = require('GraphQL');
const schema = buildSchema(`
type Query {
hello: String
}
`);
const root = { hello: () => 'Hello world' };
const app = express();
app.use('/graphql', graphqlHTTP({
schema: schema,
rootValue: root,
graphiql: true,
}));
app.listen(4000, () => console.log('Browse to localhost:4000/graphql'));

Run the below command to start graphql server:

$ node server.js

Open http://localhost:4000/graphql in your browser to checking out graphql server:

You can see above screen in your browser from where you can write a query to you graphql server.

On the left side, you can see our query parameter and on right, you can see a response from our graphql server.

Basic concept on GraphQL

Schema: Schema manages queries and mutation, defining what is allowed to be executed in graphql server. It describes the complete set of possible data (objects, fields, relationships, everything) that a client can access. Calls from the client are validated and executed against the schema. A client can find information about the schema via introspection. A schema resides on the GraphQL API server.

Queries: Used to fetch data from GraphQL server(Equivalent to GET in REST).
Mutations: Used for modifying data on the server and get updated data back(create, update, delete).
Subscriptions: Used to maintain a real-time connection with the server.

Let’s create a schema and use dummy employee list for GraphQL API request.

Let’s create schema.js file and define employee schema:

//schema.js
const {
GraphQLObjectType,
GraphQLString,
GraphQLSchema,
GraphQLInt
} = require("graphql");

Import all required data types from GraphQL module.

let’s create a sample data for the query.

const employees = [
{
id: 1,
name: 'John',
email: 'john@test.com'
},
{
id: 2,
name: 'Sunam',
email: 'sunam@test.com'
},
{
id: 3,
name: 'Rushabh',
email: 'rushabh@testGGt .com'
}
];

Now we will be defining the schema for the Employee.

const EmployeeType = new GraphQLObjectType({     
name: 'Employee',
fields: () => ({
id: {type: GraphQLInt},
name: {type: GraphQLString},
email: {type: GraphQLString}
})
});

Almost all of the GraphQL types you define will be object types. Object types have a name, but most importantly describe their fields. So we need to specify the fields for the EmployeeType. We have defined three fields for our purpose, and that is id, name, and email. It simply means that we can query the data on these three fields. Either we can get all the three fields data, or we can apply some condition to get the required data. It is the structure of our query data. So we need to define it in an EmployeeType object.

Defining Root Query

// schema.js  
const RootQuery = new GraphQLObjectType({
name: 'RootQueryType',
fields: {
employee: {
type: EmployeeType,
args: {
id: {type: GraphQLInt}
},
resolve(parentValue, args) {
for(let i=0; i<employees.length; i++) {
if(employees[i].id == args.id) {
return employees[i];
}
}
}
}
}
});

Now full code in schema.js file looks like below:

//schema
const {
GraphQLObjectType,
GraphQLString,GraphQLSchema,
GraphQLInt,
GraphQLList,
} = require('graphql');
const employees = [
{
id: 1,
name: 'John',
email: 'john@test.com'
},
{
id: 2,
name: 'Sunam',
email: 'sunam@test.com'
},
{
id: 3,
name: 'Rushabh',
email: 'rushabh@test.com'
}
];
const EmployeeType = new GraphQLObjectType({
name: 'Employee',
fields: () => ({
id: {type: GraphQLInt},
name: {type: GraphQLString},
email: {type: GraphQLString}
})
});
const RootQuery = new GraphQLObjectType({
name: 'RootQueryType',
fields: {
employee: {
type: EmployeeType,
args: {
id: {type: GraphQLInt}
},
resolve(parentValue, args) {
for(let i=0; i<employees.length; i++) {
if(employees[i].id == args.id) {
return employees[i];
}
}
}
}
employees: {
type: new GraphQLList(),
args: {},
resolve() {
return employees
}
}
}
});
module.exports = new GraphQLSchema({ query: RootQuery });

Now, let's make some changes in our server.js file, we will be importing the schema that we recently created.

const express = require('express');
const graphqlHTTP = require('express-graphql');
const { buildSchema } = require('GraphQL');
const schema = require('./schema');
const app = express
app.use('/graphql', graphqlHTTP({
schema: schema,
graphiql: true,
}));
app.listen(4000, () => console.log('Browse to localhost:4000/graphql'));

Finally, our server.js file looks like this. Now we will be restarting our server and make some request to the GraphQL server.

Make a request from the browser similar as above you will be able to get the list of employees with the property that you have requested for in the query. You can notice that you are getting only name and email property in response it is because we have queried employees with only that property. Which is a major advantage of using GraphQL server.

Similarly, we will query for only a single employee using the same endpoint.

Conclusion

GraphQL provides a complete and understandable description of the data in your API, gives clients the power to ask for exactly what they need and nothing more.

In this tutorial you’ve learned how to implement your own GraphQL server with Node.js and Express. By using the Express middleware express-graphql setting up a GraphQL server is really easy and is requiring only a few lines of code.

I will soon be publishing my next blog on using mutation on GraphQL server till then enjoy coding !!

Here is the link for the github repo where you can find all above code.

Link to my second blog is here

--

--