Create a GraphQL API with Node.js

Alan Eicker
The Startup
Published in
5 min readJan 27, 2020

RESTful APIs have long been the architectural standart for serving modern web services. And though they won’t be going away any time soon, there’s no denying that GraphQL has shaken up the way we think about and write web services.

Consumers of web services are no long bound to an API’s predefined shape, but rather have the power to control and define what a response looks like, tailoring how we present data from on user to another.

In this tutorial, we’ll create a basic GraphQL API server with Node.js and implements some of GraphQL’s features like queries and mutations.

The API Server will:

  1. Get all users,
  2. Get a single user,
  3. And add a new user.

For the sake of simplicity, we will not use a database in this tutorial. Instead, we’ll use some data hard-coded in a javascript object. Obviously, this was a very basic example. In a real world application you’d be interfacing with a database to get and modify data.

Project Setup

Before we get started building the GraphQL API server, we’ll need to install the necessary dependencies for our project.

Directory Structure

Let’s take a look at the structure for our API.

- src/
- index.js
- resolvers.js
- schema.js
- .gitignore
- package.json
  • node_modules/ will contain all of our installed node modules.
  • src/ will contain all of our server source code like the server, resolvers and schema.
  • .gitignore tells git what files to ignore when committing files.
  • Package.json contains our project specific configurations, build scripts and dependencies.

Initialize the Project

We’ll need to initialize the project first by running npm init -y. We’ll be prompted to answer some questions regarding our project. Once finished, a package.json file will be created for us in the project’s root directory

Dependencies

Our GraphQL API will require a few dependencies. Let’s install them.

npm i -S express express-graphql graphql cors

Nodemon

To make development easier and more streamlined, we’ll install a tool called nodemon, which listens to our code for changes and restarts the server. Without this, we’d have to restart the server manually after each change, so this is a big time saver.

npm i -D nodemon

ES6 Support

We’ll be leveraging ES6 modules so we’ll need to install the necessary dependencies to transpile our code into ES5 JavaScript that older browsers (e.g. IE 11) can understand.

npm i -D @babel/core @babel/cli @babel/node @babel/preset-env @babel/plugin-proposal-class-properties @babel/plugin-transform-runtime @babel/runtime-corejs3

.babelrc

We’ll create a basic .babelrc configuration file. This tells babel how to transpile out code. This is a very basic configuration. For more complicated apps that run in the browser, we can tell babel what level of feature support is needed and set up environment specific configurations.

./babelrc

Add build scripts

In order to build and run the project in development and production, we’ll need to add some scripts to the package.json file.

./package.json

Set up the GraphQL API Server

Now that the project has been set up, let’s create the GraphQL API entry point. This will configure our API and kick off our server instance.

./src/index.js

A few things are going on here:

  1. We import all of the necessary dependencies need to run our server.
  2. We specify our environment and port number;
  3. We initialize the express app and GraphQL schema.
  4. We set up the necessary middleware for the server including cors and the GraphQL endpoint. On line 19 of src/index.js you’ll notice graphiql: env === 'development'. This allows us to run the GraphiQL interface in the browser to conveniently test our queries. This feature, however will only run in development mode as specified by that line of code.
  5. Finally, we listen for out app on the specified port.

Schema

The GraphQL schema describes the functionality available to the client applications that connect to it. It specifies the data types that are accepted in our queries and mutations.

./src/schema.js

Resolvers

GraphQL resolvers are a collection of functions that generate responses for queries and mutations.

Like I mentioned above we’ll create three resolvers.

  1. Get all users,
  2. Get a single user,
  3. And add a new user.

./src/resolvers.js

Runt the API Server

Now that the GraphQL API server is complete, lets run the server and test our API.

Run the following command:

npm run start

Navigate to http://localhost:3030/graphql in the browser and you should see the GraphiQL interface.

Testing the API

Let’s test out API to make sure it works as expected.

First we’ll test the users query. Enter the following query in the left panel and click run:

{
users {
id,
name:
email
}
}

This should return some data in the right side panel.

Next we’ll test the user query. Enter the following query in the left panel and click run:

{
user(id:1) {
id,
name,
email
}
}

This should return some data in the right side panel.

Finally, we’ll test the addUser mutation. Mutations are different than queries in that they are used to modify data. Enter the following query in the left panel and click run:

mutation {
addUser(name: “Fred”, email: “fnelson@gmail.com”) {
createdId
}
}

This should return some data in the right side panel.

Wrapping Up

There you have it. Your very first GraphQL API! You can use this as a boilerplate for a real-world project and tie in a database like MongoDB to handle your data. Feel free to fork the repo below for your own projects.

Project Source Code

https://github.com/alaneicker1975/tutorial-graphql-api

I hope you enjoyed this tutorial. Cheers!

--

--

Alan Eicker
The Startup

Lead Front-End JavaScript Engineer, React, Node.js, Accessibility Advocate https://www.alaneicker.com/