Simple API with NodeJS & Express

Pritam Ajmire
4 min readApr 1, 2023

--

Summary

This is quick starter guide to create RESTful API with NodeJS & Express. We will develop endpoints for Create, Read, Update & Delete operations. This tutorial consider in-memory array of Books object for CRUD operations.

This tutorial is very basic tutorial to create REST API.

Before you start, make sure Node installed in your system. If not, go to ttps://nodejs.org/en/download/ to download and install it.

Verify Node is installed in your system using below commands in terminal. This command let you know the Node version installed in your system.

node -v

Initialize Application

Create a new folder for your project.

mkdir node-basic-api
cd node-basic-api

For NodeJS project, we need to have package.json file, which contains project name, version, script and all dependencies etc.

npm init -y

The above commands creates a package.json & package-lock.json under “node-basic-api” folder. package.json file contains data as shown below.

{
"name": "node-basic-api", // name of application
"version": "1.0.0", // veriosn of the application
"description": "", // description of the application
"main": "index.js", // application entrypoint file
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1" // some scripts
},
"keywords": [], // keywords to find packages.
"author": "", // author of the application
"license": "ISC" // license information
}

Create “src” folder, as all code should go into it.

mkdir src

Create “index.js” file in “src” folder & add below code.

// src/index.js
console.log("hello world")

Run the application using below command in terminal. This command will show an output as “hello world” on the console.

node index.js

Setup Express and the API

To create REST API we need to install Express package using below command.

npm install express

Replace “index.js” file with below code. This code start the express server on port 3000 & has an endpoint on path “/”.

// src/index.js
// import the express
const express = require("express");

// define the Express application
const app = express();
app.use(express.json());

// define an endpoint with "/" path
app.get("/", (req, res) => {
res.send("Welcome to node-basic-api");
});

// start the server
app.listen(3000, () => {
console.log("listening on localhost:3000");
});

To start application, run the command again

node src/index.js

The above command should show output as below.

listening on localhost:3000

Open any browser and enter URL as localhost:3000 . You should see response as “Welcome to node-basic-api” in the web browser.

Create API

In this tutorial, we will create CRUD operation for books with in-memory collection of books.

GET Endpoint : Get all books

This is API for get all books. We will read from books array & send all the element from books array in response.

// index.js
// import the express
const { json } = require("express");
const express = require("express");

// define the Express app
const app = express();
app.use(express.json());

// define an endpoint
app.get("/", (req, res) => {
res.send("Welcome to node-basic-api");
});


// define in-memory books array
let books = [
{
id: 1,
title: "Learning JavaScript Design Patterns",
pages: 200,
},
{
id: 2,
title: "You Don't Know JS Yet",
pages: 230,
},
{
id: 3,
title: "Pro Git",
pages: 450,
},
];

// Endpoint : Get all books
app.get("/books", (req, res) => {
res.send(books);
});



// starting the server
app.listen(3000, () => {
console.log("listening on localhost:3000");
});

Testing GET /books endpoint with postman.

POST Endpoint : Add a new book

This endpoint is to add new book in existing books collection.

app.post("/books", (req, res) => {
const newBook = { id: books.length + 1, ...req.body };
books.push(newBook);
res.status(201).send(books);
});

Testing POST /books endpoint with postman

PUT Endpoint : Update an existing book

This endpoint is to update value of existing book. We will perform below steps.

  • To update existing book, endpoint will accept book id in query parameter.
  • We need to search existing book by its id in books array, if not found we will respond with 404 status code & error message.
  • Update values of existing book with new values from body.
app.put("/books/:id", (req, res) => {
const book = books.find(item => item.id === parseInt(req.params.id));
if (!book) return res.status(404).send(`The book with the id (${req.params.id}) was not found.`);
book.title = req.body.title; // update title
book.pages = req.body.pages; // update pages
res.send(book);
});

DELETE Endpoint : Delete an existing book

This endpoint is to delete existing book. We will perform below steps.

  • To delete existing book, endpoint will accept book ID in query parameter.
  • We need to search existing book by its ID in books array, if not found we will respond with 404 status code & error message.
  • Delete the book from array.
app.delete("/books/:id", (req, res) => {
const book = books.find(item => item.id === parseInt(req.params.id));
if (!book) return res.status(404).send(`The book with the id (${req.params.id}) was not found.`);
const index = books.indexOf(book);
books.splice(index, 1); // delete the book at index
res.send(book);
});

What is Next

I have written another article on refactoring of this code here. Have a look!

--

--