Build a REST API with Node.js: Design & Plan Your API
Tags: node, restapi, mongodb, javascript
Published: 2020-12-29 06:01:17

---
title: Build a REST API with Node.js: Design & Plan Your API
published: true
date: 2020-08-01 23:39:59 UTC
tags: Nodejs,RESTAPI,MongoDB,JavaScript
canonical_url: https://lo-victoria.com/build-rest-api-with-nodejs-design-and-plan-restful-api
---

Hello everyone! Welcome to the first article of an exciting new series called [Let's Build a Node.js REST API](https://hashnode.com/series/lets-build-a-nodejs-rest-api-ckcov1aob00dcfms19o5g2x42). In this series, I will be going through a step-by-step tutorial on how you can plan, design and build your very own REST API using Node.js!

### Before we start...
Some prerequisites you need to follow along:
- Beginner to intermediate knowledge in JavaScript
- Basic understanding of what REST APIs are
- Basic understanding of back-end programming and Node.js

> Read my articles on [REST APIs](https://lo-victoria.com/a-deep-look-into-restful-apis-ckbty1p650043las1fs38agwj) and [Back-end Programming](https://lo-victoria.com/a-beginners-intro-to-back-end-programming-ckanyrk7d02b2bbs1g9fv127k) if you need a quick refresher.

### Heads up! Some tools we will use:
- Visual Studio Code or any text editor
- POSTman
- Node.js and express
- MongoDB Atlas

For now, you** just need to have a text editor installed** in your computer. I'll explain how to install the rest in this series.

## Step 1: Planning our T-API
For this tutorial, we will be making a simple API for tea (so random I know). I call it **T-API** because it sounds like "Tea API".

To plan an API, we must first understand what we want it to do. We can write down **user stories** to help us determine what we need in our API design.

### Our T-API User Stories
1. I can create a new tea object and add it to the database
2. I can get all the tea from the database
3. I can delete all the tea in the database
4. I can get a single tea by querying its name
5. I can post a comment to a single tea
6. I can delete a single tea from the database

### Our Tea Object
Based on our user stories and how we want to use the API, we can draft a sample tea object that the API can return. This helps us to decide what properties to include in the object early in the stage of making this API. So, for T-API, a tea object might look like:
```
{
    "name": "Jasmine Tea",
    "image": "an image file url",
    "description": "Jasmine tea (茉莉花茶) is tea scented with the aroma of jasmine blossoms.",
    "keywords": "aromatic, china, sweet",
    "origin":"China",
    "brew time": 2,
    "temperature": 80,
    "comments": []
}
```
## Step 2: Designing Structure for T-API
The way to design an API is to visualize its **routes** and **request methods**.

Now that we have understood what we want T-API to do for us, we can come up with a design like so:

| Routes | HTTP Methods| Description
|:------- |:---------------|:--------------
| /tea      | GET                  | Displays all tea
| /tea      | POST               | Creates a new tea
| /tea      | DELETE            | Deletes all tea
|/tea/:name| GET     | Displays a specific tea, given its name
|/tea/:name| POST  | Adds a comment to a specific tea, given its name
|/tea/:name| DELETE | Deletes a specific tea, given its name

Okay, we have planned and designed our T-API, let's get started with setting up the project!

## Step 3: Install Node.js and npm
Download Node.js (with npm) at: https://nodejs.org/en/download/

After it is installed, to check if it is there, go to your command prompt:
```
node -v
npm -v
```
## Step 4: Initialize project
Create a new project file and in the root directory, initialize npm by running the following code in the command line:
```
npm init
```
Answer the questions that follow and a `package.json` file will be created.

## Step 5: Install express
Let's install **express** and save it to our `package.json` by running:
```
npm install --save express
```

## Step 6: Create server
Now, we create a `server.js` file in our project's root directory to take care of the back-end. First, we have to create an Express app with:
```
const express = require("express");
const app = express();
```
Now we can add the code after:
```
app.use(express.json()); // parses incoming requests with JSON payloads
```
Then, below it, our listener to ask our server to listen for a request. 
```
const listener = app.listen(process.env.PORT || 3000, () => {
    console.log('App is listening on port ' + listener.address().port)
})
```
By default, we want to listen on port 3000. However, in cases where the port number is designated from an environment variable, the app will listen on `process.env.PORT`.

## Try a test run!
So now that we have our server.js set up, let's try running the server by entering 
```
node server.js
```
into the command line. If it works, you should see the console outputs a message telling you which port it is listening to.

![server.PNG](https://cdn.hashnode.com/res/hashnode/image/upload/v1594945824965/3aeDW2WBB.png)

## That's all for now!
Thanks for reading the first article of the series. Technically, I can write about building a REST API into 1 article but it will be too long and I will have to leave out a lot of important details which may confuse code newbies. 

I hope this has been a helpful read for you. Be sure to **like, share this article and stay tuned** for the next part where we will start creating our routes and setting up our database in Mongo Atlas! In the meantime, please **ask any questions** in the comments below and read up on the frameworks/concepts/technologies in this article to accelerate your learning. Till next time, cheers!

--------
## Glossary
Here are some potentially unfamiliar words I have used in this article. Feel free to read slowly and read the suggested articles for further details.

### user stories
According to [Wikipedia](https://en.wikipedia.org/wiki/User_story), a user story is an informal, natural language description of one or more features of a software system. User stories are often written from the perspective of an end user or user of a system.

### routes
Routes are represented as URIs in REST APIs. For example, the index route for an API is '/'. Other routes will be built on it such as '/names' for a route that returns all names or '/pages' for one that returns all pages. 
Read up on basic routing [here](https://expressjs.com/en/starter/basic-routing.html).

### request methods
Request methods refer to the HTTP methods which specifies the desired action the browser wants to do with the server. Read my article on the [Basics of HTTP Requests](https://lo-victoria.com/the-basics-of-http-request-methods-ckb1noib903iel6s1582lccg9) for more details. 

### express
Express is web framework for Node.js to allow easy and robust routing for back-end development. It will be used to create our routes and handle our HTTP requests and any **middleware** for our API. You can read more in its documentation [here](https://expressjs.com/).

### middleware

![middleware.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1594942772687/f1tkx-LGQ.png)

A middleware essentially refers to the software that sits between the client-side requests and the server-side resource. It handles data, provide API management, messaging services as well as authentication. For more information, read up [here](https://en.wikipedia.org/wiki/Middleware).

---------
### Further Reading
- [Bonus Part 1.5 of the series: HTTP Module and Express](https://lo-victoria.com/build-a-nodejs-api-for-beginners-15-http-module-and-express-ckdd2168w006xyss1atvia0on)
- [About REST APIs](https://lo-victoria.com/a-deep-look-into-restful-apis-ckbty1p650043las1fs38agwj)
- [Intro to Back-end Programming](https://lo-victoria.com/a-beginners-intro-to-back-end-programming-ckanyrk7d02b2bbs1g9fv127k)
- [Basics of HTTP Requests](https://lo-victoria.com/the-basics-of-http-request-methods-ckb1noib903iel6s1582lccg9)
- [About Routes](https://expressjs.com/en/starter/basic-routing.html)
- [Express Documentation](https://expressjs.com/)
- [About Middleware](https://en.wikipedia.org/wiki/Middleware)