How to set-up a powerful API with Nodejs, GraphQL, MongoDB, Hapi, and Swagger

Image for post
Image for post

Separating your frontend and backend has many advantages:

I’m all for hiring juniors and training your staff, and that’s exactly why you should separate concerns. With the separation of concerns, you can reduce the complexity of your application by splitting responsibilities into “micro-services” where each team is specialized in their micro-service.

Note; If you’re new to building APIs, I recommend reading through this book.

As mentioned above, the on-boarding/ramp-up process is much quicker thanks to splitting up responsibilities (backend team, frontend team, dev ops team, and so on)

Image for post
Image for post
Maurice Moss from “IT Crowd”

Forward thinking and getting started

We will be building a very powerful, yet flexible, GraphQL API based on Nodejs with Swagger documentation powered by MongoDB.

The main backbone of our API will be Hapi.js. We will go over all the technology in substantial detail.

At the very end, we will have a very powerful GraphQL API with great documentation.

The cherry on top will be our integration with the client (React, Vue, Angular)

Prerequisites

Let’s goo!

Open the terminal and create the project. Inside the project directory, we initialize a Node project.

Creating our project

Next, we want to set up our Hapi server, so let’s install the dependencies. You can either use Yarn or NPM.

Image for post
Image for post

Before we go on, let’s talk about what hapi.js is and what it can do for us.

Image for post
Image for post

hapi enables developers to focus on writing reusable application logic instead of spending time building infrastructure.

Instead of going with Express, we are going with Hapi. In a nutshell, Hapi is a Node framework. The reason why I chose Hapi is rather simple — simplicity and flexibility over the boilerplate code.

Hapi enables us to build our API in a very rapid manner.

Optional: check out this quick crash course on hapi.js:

The second dependency we installed was the good-ole nodemon. Nodemon restarts our server automatically whenever we make changes. It speeds up our development by a big factor.

Let’s open our project with a text editor. I chose Visual Studio Code.

Setting up a Hapi server is very straightforward. Create a index.js file at the root directory with the contents of the following:

Image for post
Image for post

If you’re unsure about async await — watch this:

funfunfunction async await explanation
Image for post
Image for post

Now, if we head over to http://localhost:4000 we should see the following:

Image for post
Image for post

Which is perfectly fine, since the Hapi server expects a route and a handler. More on that in a second.

Let’s quickly add the script to run our server with nodemon. Open package.json and edit the scripts section.

Image for post
Image for post

Now we can do the following 😎

Routing

Routing is very intuitive with Hapi. Let’s say you hit / — what would you expect to happen? There are three main components in play here.

Image for post
Image for post

Inside the init method we attached a new method to our server called route with options passed as our argument.

If we refresh our page we should see return value of our root handler

Image for post
Image for post

Well done, but there is so much more we can do!

Setting up our database

Right, next up we are going to set up our database. We’re going to use mongodb with mongoose.

Image for post
Image for post

Let’s face it, writing MongoDB validation, casting and business logic boilerplate is a drag. That’s why we wrote Mongoose.

Image for post
Image for post
Image for post
Image for post

The next final ingredient related to our database is mlab. Instead of running mongo on our local computer, we are gonna use a cloud provider like mlab.

The reason why I chose mlab is because of the free plan (useful for prototyping) and how simple it is to use. There are more alternatives out there, and I encourage you to explore all of them ❤

Image for post
Image for post
mlab (free)

Head over to https://mlab.com/ and signup.

Let’s create our database.

And finally, create a user for the database. That will be all we will be editing on mlab.

Connecting mongoose with mlab

Open index.js and add the following lines and credentials. We are basically just telling mongoose which database we want to connect. Make sure to use your credentials.

Image for post
Image for post

If you want to brush up your MongoDB skills, here’s a solid series.

If everything went according to the plan, we should see ‘connected to database’ in the console.

Image for post
Image for post

Woohoo!

Good job! Take a quick break and grab some coffee, we are almost ready to dive into the “cool parts”.

Creating Models

With MongoDB, we follow the convention of models. In other words — data modeling.

Image for post
Image for post
https://docs.mongodb.com/manual/core/data-modeling-introduction/

It’s a relatively simple concept which you will be able to grasp. Basically, we just declare our schema for collections. Think of collections as tables in an SQL database.

Let’s create a directory called models. Inside we will create a file Painting.js

Painting.js is our painting model. It will hold all data related to paintings. Here’s how it will look:

Image for post
Image for post

Let’s fetch all of our paintings from the database

First, we need to import the Painting model to index.js

Image for post
Image for post

Adding new routes

Ideally, we want to have URL endpoints reflecting our actions.

such as /api/v1/paintings/api/v1/paintings/{id} — and so on.

Let’s start off with a GET and POST route. GET fetches all the paintings and POST adds a new painting.

Image for post
Image for post

Notice we modified the route to be an array of objects instead a single object. Also, arrow functions 😊

If we head over to http://localhost:4000/api/v1/paintings we should see an empty array.

Image for post
Image for post

Why empty? Well, we haven’t added any paintings just yet. Let’s do that now!

Image for post
Image for post
https://www.getpostman.com/ (free)

Install postman, it’s available for all platforms.

After installation, open postman.

Image for post
Image for post
Sample data

POST paintings

Alright. Good to go! Let’s open http://localhost:4000/api/v1/paintings

Image for post
Image for post
GET paintings

Excellent! We still have some way to go! Next up — GraphQL!

Here’s the source code just in case anyone needs it :-)

Written by

Software engineer, tech journalist, startups. Stay up to date https://thewholesome.dev, www.startupscrushing.com Twitter @ https://twitter.com/lasnindrek

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store