Hello everyone! Welcome to the first article of an exciting new series called Let's Build a Node.js REST API. 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 and Back-end Programming 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
- I can create a new tea object and add it to the database
- I can get all the tea from the database
- I can delete all the tea in the database
- I can get a single tea by querying its name
- I can post a comment to a single tea
- 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: 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.
Before we wrap up, I have a question...
In order to make this series as beginner-friendly as possible, I added a "Glossary" right below a potentially unfamiliar word to explain it (i.e. express, middleware, etc). Do you like this structure or do you prefer all Glossary terms to be at the end of an article? Please let me know in the comments. Thanks!
Edit: A kind reader told me to put all the glossary at the end, so please find it at the end of this article.
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, 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.
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 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.
middleware
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.