Create a RESTful API in NodeJS

by Matt Heff

Ever wanted to create your very own API or do you just need some syntax for something that you are currently working on? Well we have you covered!

Tools you will need

  • Visual Code
  • Command line
  • Node / npm installed
  • Postman ( or some way to interact with the API)

Navigate to the directory you want to set up this project in

cd /home/heff/Code/NodeJS/ApiTutorial-Simple
npm init
npm install express cors
code .

Create Products.JSON

Create a file name products.json in the root directory and put the following JSON into it, this is a simple product database that we will read/update/create/delete ( get, put, post, delete ).

I have no intention of permanently altering this data, we will load it into the memory of the service and then modify it but after the service is terminated nothing will be retains. This is especially helpful once we start deleting.

    "id": "Prod1",
    "name": "Online Product #1",
    "type": "online",
    "qty": null,
    "price": 10.5
    "id": "Prod2",
    "name": "Shipping Product #2",
    "type": "physical",
    "qty": 55,
    "price": 17.5,
    "shipping_price": 10
    "id": "Prod3",
    "name": "Online Course Product #3",
    "type": "physical",
    "qty": 55,
    "price": 17.5,
    "shipping_price": 10

Create a Server.js file

Create a server.js file and this is the one we will be having node execute for us we will put together in sections and test along the way the sequence will be

  • Load the Products Data
  • Initialise the API Service
  • Create GET
    • Get All
    • Get by ID
  • PUT
  • POST

ok now we are ready to GetCoding!

Load the Products Data

Run: node server.js

let products = require("./products.json");


use the command node sever.jsAfter that you should see the products JSON object written to the console like in the image below

Great! Now lets make a service that will listen to us

Initialise the API Service

Add the following code to your server.js file what we are doing here is getting our service setup and configured so it will sit and listen for instruction i have included some CORS handling incase anyone tries to do test this via their browser console instead of postman

const express = require("express");
const cors = require("cors");
const app = express();

var corsOptions = {
  origin: "http://localhost:9999",

// parse requests of content-type - application/json
// parse requests of content-type - application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: true }));

//Insert GET/PUT/POST/DELETE functions in this section

//Get functions
app.get("/product", function (req, res) {

app.get("/product/:id", function (req, res) {
  let item = products.find((product) => ===;

//put functions

// post functions

// delete functions


var server = app.listen(9999, function () {
  var host = server.address().address;
  var port = server.address().port;
  console.log(`Simple API listening on host: ${host} with port: ${port} `);

if you run this now you will have a service start up and sit there listening on port 9999, how cool is that!

You can use postman now to perform a get on

  • http://localhost:9999/product
  • http://localhost:9999/product/Prod1

Postman gives the following results,

At this stage you now have a very basic API! If this is your first time congratulations! I hope you remember me!

Try out looking for Prod2 & Prod3 even a Prod4 that does not exist to see what happens.


Add the following code under the comment //PUT functions

Here we need to make sure the data send to us is not empty, from there we look for where our item is in the product list and once we find it ( assuming we do ) we will update it with the JSON sent, the whole record must be sent, sending only partial data will result in data missing.

app.put("/product/:id", function (req, res) {
  if (!req.body) {
      message: "Content can not be empty!",
  //find the product by id and update it 
  let index = products.findIndex((x) => ==;
  products[index] = req.body;



Add the following code under the comment //POST functions

Here we need to make sure the data send to us is not empty, from there we look for where our item is in the product list and if we don’t find it we create a new one otherwise let them know one already exists."/product", function (req, res) {
  if (!req.body) {
      message: "Content can not be empty!",
  // check to see if there is a product that exists with that id
  let index = products.findIndex((x) => ==;
  if (index !== -1) {
      message: `Item already exists wth the ID: ${}`,
  //add new product to the list 


Add the following code under the comment //DELETE functions

The code below looks for a matching product with the value that was passed to it and if it finds one it will remove it from the product list.

app.delete("/product/:id", function (req, res) {
  //here we remove the product from our list if it is found
  let tmp = products.filter((item) => !==;
  products = tmp;


You can find the code for this in github as well as a collection from postman so you can test out the API

GitHub Repo

Related Posts