Getting Started With GraphQL in express

Getting Started With GraphQL in express

In this article, I’ll be walking you through the basics of GraphQL in express.

GraphQL is a query language for API’s and it’s more powerful. It allows the client to access only what they need, making the access rate faster.

Let’s get started!

Create a new folder and cd to the folder.

$ mkdir graphql-test
$ cd graphql-test

Initialize the npm package, using npm init

$ npm init

Install necessary modules

$ npm i express express-graphql graphql

Then, create index.js file and import the express module and make sure the app is listening to the port specified.

const express = require('express');

const app = express();

app.listen(3000, () => console.log("Server running at port 3000"));

To get started with the GraphQL part, let’s define the documents that we are going to work with.

const subscribersList = [
{ id: 1, name: "Ron", email: "[email protected]", country: "US" },
{ id: 2, name: "George", email: "[email protected]", country: "NZ" },
{ id: 3, name: "Fred", email: "[email protected]", country: "UK" }
];

Since the objects in the list are of Javascript’s primitive type, we have to define those objects as a GraphQL object.

const SubscriberObject = new GraphQLObjectType({
name: 'subscriber',
description: 'A single Subscriber object',
fields: () => ({
return ({
id : { type: GraphQLNonNull(GraphQLInt) },
name : { type: GraphQLNonNull(GraphQLString) },
email : { type: GraphQLNonNull(GraphQLString) },
country : { type: GraphQLNonNull(GraphQLString) }
})
}
});

In the fields method, the properties of the object is mentioned along with its type. The type of id is represented as GraphQLInt and similarly for other properties.

By enclosing the type of data in GraphQLNonNull(), we are declaring that the value should not be null.

These properties must be imported from GraphQL package before use.

const { GraphQLSchema, GraphQLObjectType, GraphQLNonNull, GraphQLInt, GraphQLString, GraphQLList } = require('graphql');

And with that, we are going to create a new query that lists all kinds of queries in a particular route. We call it rootQuery.

const RootQuery = new GraphQLObjectType({
name: 'rootQuery',
description: 'Root Query',
fields: () => ({
subscribers: {
type : GraphQLList(SubscriberObject),
description : 'List of all Subscribers',
resolve : () => subscribersList
}
})
});

In the fields method, the query to get all subscribers is defined. And using the resolve method, we can specify the set of processes that it is to be carried out.

Now, we should specify the query in a Schema that we are going to utilize. Let’s define a Schema now. We will be using GraphQLSchema from GraphQL package to define a Schema.

const subscriberSchema = new GraphQLSchema({
query: RootQuery
});

We will be observing our results using GraphiQL. GraphiQL provides an interface to test and experiment with graphQL queries, which will be very useful to understand the working of GraphQL as a beginner.

To use graphiql, we will be using graphqlHTTP method from express-graphql module

const { graphqlHTTP } = require('express-graphql');

app.use("/graphql", graphqlHTTP({
graphiql : true,
schema : subscriberSchema
}));

Here, providing graphiql value as true, allows us to use graphiql. The schema which we defined earlier, is specified in the schema property.

Now, you can run the file in the terminal.

$ node index.js

Go to http://localhost:3000/graphql , to view and test our code.

Let’s try requesting only the email value for all the subscribers.

Queries in GraphQL are used to get documents, and if we want to make some modifications to our data, we can use Mutations.

Mutations can be defined in the same way as we did for Queries.

const RootMutation = new GraphQLObjectType({
name: 'RootMutation',
description: 'Root Mutation',
fields: () => ({
addSubscriber: {
type: SubscriberObject,
description: 'Add a new subscriber',
args: {
name : { type: GraphQLNonNull(GraphQLString) },
email : { type: GraphQLNonNull(GraphQLString) },
country : { type: GraphQLNonNull(GraphQLString) }
},
resolve: (parent, args) => {
const aSubscriber = {
id : subscribersList.length + 1,
name : args.name,
email : args.email,
country : args.country
}
subscribersList.push(aSubscriber);
return aSubscriber;
}
},
})
});

The arguments that are going to be received by the mutation are specified along with its type in the args property.
resolve
method takes args as the second parameter. The args (arguments) are used to get data from the request which in this case name, email and country.

Finally, we have to specify the mutation we defined, in the schema.

const subscriberSchema = new GraphQLSchema({
query: RootQuery,
mutation: RootMutation
});

Let’s try to add a new Subscriber!

Now, when we use subscribers query to get all subscribers, we could see a new subscriber added to the list.

Github code link: https://github.com/SharmilaS22/medium-graphql-express

Thanks for reading!