Creating a basic REST API with Node.js from scratch!

Mujawar Faiyaz Aziz
The Startup
Published in
7 min readJun 10, 2020

If you are trying to dive into the world of web development, then it’s quite sure that you would have came across the phrase “REST API”. There’s a lot of buzz around the term and everyone seems to be talking about the API and all that stuff. And if you have been thinking what that stuff it is, then you might be in the right place! Because today, we’re going to discuss the same.

This is gonna be a beginner-friendly blog, meant for the people having no prior experience with Node.js.

What is REST API?

First, let us start by describing what REST actually is. REST stands for REpresentational State Transfer. And the API stands for Application Program Interface. Wait, what did I just say?! Don’t worry guys! However heavy the terms might sound, it’s actually quite simple! REST is nothing but software architecture design that is used for creating the web services. Most commonly used with HTTP requests, REST API, i.e the web service, provides resources, like files or data in JSON or XML format, to the clients requesting it.

REST APIs work with HTTP Verbs( GET , POST , PUT , PATCH & DELETE )

Defining HTTP Verbs:

GET: As name suggests, this is used to get resource from web.

POST: This is used to add new resources to the web service.

PUT/PATCH: This is used to update any resource already present on the web service.

DELETE : This is used to delete any web resource from the web service.

What are we building?

We will be building a very simple REST API for a blogging site to demonstrate the CRUD(Create, Read, Update, Delete) operations. Our API will return the data in JSON format, as it is simpler to work with. We will be sending our requests to our API through Postman .

How do I do it?

Having described what a REST API is, let’s move forward to creating it! In this tutorial, we’re gonna build the API on Node.js. We will be using Node.js with the express.js javascript library to build a basic REST API. So, let’s get going

Before proceeding any further, make sure you have properly installed Node.js on your system. If not, you can download and install it from here.

First, open terminal and type the following commands:

mkdir rest-api
cd rest-api

This creates a folder named ‘rest-api’, which we would be using as our project folder.

Then type the following command:

npm init -y

npm — node-package-manager — comes bundled with Node.js and is used to install packages from the npm registry.. This command creates a package.json file that lists all the npm packages installed.

Open the folder in any code editor of your choice. I would be using Visual Studio Code.

For creating the REST API, we will be needing a few npm packages.Run the following commands to install the required packages:

npm install express mongoose
npm install -D nodemon

When building REST API with Node.js, express.js is like the de facto library to go to. Also, ‘mongoose’ is the library used for our API to interact with the MongoDB database. Nodemon is used to re-run our API automatically everytime changes are made into the code, which would otherwise had to be done manually everytime. You may wish to read more about mongoose and express here.

So,let’s begin with the interesting part? Create a file named ‘index.js’ and write the following code into it:

index.js — skeleton of our server

Here, we have just imported the express and mongoose library, and created an instance of server. The server is then started on port 3000.

To run the server i.e our API, run the command:

nodemon index.js

This gives the output:

Now let’s give some functionality to our bare-bone server. Create a folder named ‘models’, and into that folder, create a file named ‘Post.js’. Write the following code into it:

Post.js — The structure of data to be stored

Once we have finalized the database schema, we are now ready to create the routes for our API. In the index.js file, write the following code:

functionality to get all posts stored in the database

Here, we have defined the ‘route’ to get all the posts stored in our database. ‘Route’ is the URL that you would type in the search bar of a browser. This route handles a GET request. On getting request on this route, our API will search the database and fetch all the post stored in there, and return them all in JSON format:

As currently we don’t have any post stored, we get an empty array as a result

Express.js provides convenient methods for handling the HTTP requests(namely get(),post(),put(),patch() and delete()). These methods have two parameters: a string representing the route, and a function to execute when a request is received. This function, in JavaScript world, is called as Callback Function. It has two parameters: first parameter represents the request object, and the second representing the the response object.

Done with reading all the posts? Now let’s put some of our posts in there! Write the following code in index.js file:

functionality to add post in the database

What we’re doing here is just defining another route to save a post. This route handles a POST request. We send the post details in JSON format to the API. The API extracts all the information as stores it in the database as a ‘post’, and return the response as follows:

Response received when post was saved successfully

If we now request our server to fetch all the posts, it would respond us with:

Response with all the posts

Now let’s move ahead with our API. Next, we write a route to get a specific post based on the post-ID we specify,i.e handling a GET request. In index.js, continue with:

functionality to get post with specified ID

When a request hits our API at this route, it goes to the database, looks through all the posts and returns the post that has the same ID as provided. The response is as follows:

Response received with the requested Post

If no post with the specified post is found, the server will responds with:

{
"msg" : "No post found"
}

Now, let’s define a route to update the post details! The API, on getting a request on this route will find the post with specified ID, and then updates the post title with the new one. If you have paid attention, this is the handling of PUT request! In your index.js file:

functionality to update post details

Hitting the API with this route will result in the following response

Title is updated

Having posted our thoughts, what if we wished to delete our post? Currently there’s no way to tell our API to remove any post. Never mind! We are programmers. We can fix that! Write the following code in your index.js file:

functionality to delete post with specified ID

On receiving a request here, our API searches the database and deletes any post that has the ID as we provided. Pretty easy, huh ?! This handles the DELETE request.

Response received when requested post gets deleted

Ahem, guess what? Hereby we have successfully created our first REST API!! You have successfully implemented the basic CRUD operations through an API, which is the basis of all web services development. Feeling great, yeah ?!

Here’s the complete index.js file for you to go through:

index.js — complete file

Young devs! This surely not the most complete introduction to REST APIs. But I think it’s good enough to get you all started. This is just the first stepping stone. Ahead there’s a hell lot more to learn. Hope you are prepared for it. And, Good Luck!

Please give a clap if you find it helpful! It gives a me kick! 😁

--

--