Skip to main content

Building RESTful APIs with Node.js, Express & MongoDB

In this article, we will explore how to build RESTful APIs using Node.js and Express. We'll utilize several standard libraries and tools:

Node.js: Node.js is a cross-platform, open-source JavaScript runtime environment. It runs on the V8 JavaScript engine and allows developers to execute JavaScript code outside of a web browser. Node.js is widely used for building command-line tools and server-side scripting.

Express.js: Express.js is a backend web application framework for Node.js, designed to build web applications and RESTful APIs. It is free, open-source software released under the MIT License.

Babel: Babel is a free and open-source JavaScript transcompiler. It converts ECMAScript 2015+ code into backward-compatible JavaScript code that can run on older JavaScript engines, enabling developers to use the latest language features.

MongoDB: MongoDB is a cross-platform, document-oriented NoSQL database program. It stores data in JSON-like documents with optional schemas, making it flexible for modern applications.

Postman: Postman is a popular tool for working with APIs. It provides an easy interface to make HTTP calls, test endpoints, and run scripts during various phases of API development.

Studio 3T: Studio 3T is a powerful and user-friendly GUI for MongoDB, offering advanced features to help manage and visualize MongoDB databases.

1) Project Setup

HereĆ¢€™s a step-by-step guide to creating, installing, and starting a Node.js and Express project:

1) Install Node.js & Express

Visit the official Node.js website. Download and run the installer for your operating system (e.g., macOS, Windows, Linux). The installer includes Node.js and npm (Node Package Manager).

Verify the installation by running the following commands in your terminal or command prompt:


node -v
# Example output: v20.16.0

Next, create your project directory:

cd ~/Desktop
mkdir nodejs-mongo-apis
cd nodejs-mongo-apis

Initialize a package.json file:

npm init

You can customize the generated package.json or use the default settings. Here's an example:

Install Express.js: Before installing Express.js, make sure Node.js and npm (Node Package Manager) are installed on your system. Use npm to install Express.js by running the following command:

npm i express

Now, you have initialized your project, installed Node.js (which comes with npm), and installed Express.

2) Install MongoDB

Go to the official MongoDB download page and choose the appropriate version for your OS (Windows, macOS, Linux).

If you're using macOS, you can install MongoDB Community Edition using Homebrew:

brew tap mongodb/brew
brew update
brew install mongodb-community@7.0
brew services start mongodb-community@7.0

Use the mongosh command to start the MongoDB shell:

mongosh

By default, mongosh connects to your local MongoDB server running on localhost at port 27017.

You can use Studio 3T to visualize and manage your MongoDB databases.

3) Install Mongoose

Mongoose is an object data modeling (ODM) library for MongoDB and Node.js. Install it using npm:

npm i mongoose

4) Install Babel

Babel is a JavaScript compiler that allows you to use the latest JavaScript features. Install Babel locally:

npm i --save-dev @babel/core @babel/cli @babel/node @babel/preset-env

5) Install Nodemon and Body-Parser

Nodemon is a utility that monitors for any changes in your source code and automatically restarts your server. Install Nodemon as a development dependency:

npm install --save-dev nodemon

Body-Parser is middleware for parsing incoming request bodies in a middleware before your handlers, available under the req.body property. Install Body-Parser as a dependency:

npm install body-parser

HereĆ¢€™s how your updated package.json should look:

6) Create Configuration for Babel

Create a .babelrc file (or babel.config.js) in the root directory of your project to configure Babel:

{ "presets": [ "@babel/preset-env" ] }

This configuration enables Babel to trans compile your modern JavaScript code into a version compatible with older JavaScript engines.

7) Change package.json File for Nodemon

Let's update our package.json file to include a new script for starting the server using Nodemon. This script will allow us to automatically restart the server whenever we make changes to our files.

Add the following line to the "scripts" section:

"scripts": { "start": "nodemon ./index.js --exec babel-node" }

Here's how your updated package.json should look:

8) Create index.js

Next, let's create a file called index.js. This file will serve as the entry point for our application:


9) Run the Server

You can now start the server using the npm start command. This will run the predefined command specified in the "start" property of the scripts object in package.json:

npm start

You should see the following output in your terminal:

Server is running on port: 3000

Node.js REST APIs CRUD

Here's a step-by-step guide to creating a Node.js REST API with CRUD (Create, Read, Update, Delete) operations:

1) Folder Structure

Create a src folder along with subfolders for models, routes, and services. Inside these folders, you'll create .js files as shown below:

2) Update index.js

Modify your index.js file to delegate routing responsibilities to appRoutes.js. The updated index.js should look like this:

3) Add Routes

Create CRUD routes for 'user' in the appRoutes.js file:

4) Test in Postman

Ensure your Node.js application is running and listening on a specific port. Then, you can test the CRUD APIs using Postman.

Node.js with MongoDB REST APIs CRUD

MongoDB is a NoSQL database that stores data in collections, where each collection contains documents resembling JSON objects. In our REST APIs, each 'user' will be represented by a document in MongoDB.

1) Add MongoDB Configurations

Update index.js to add a connection to MongoDB using Mongoose and set up body-parser middleware:

2) Create a Schema

Create a user.js file inside the models folder to represent the user schema:

3) Add CRUD Logic for Node.js + MongoDB

In the services folder, create an appService.js file and add the logic for CRUD operations using MongoDB:

4) Update Routes

Update appRoutes.js to call the functions from appService.js instead of returning static messages.

5) Test in Postman

Now, test your CRUD APIs with Postman to ensure everything is working correctly.

Source Code: GitHub

Comments

Popular posts from this blog

Deploying Spring Boot microservices on Kubernetes Cluster

This article guides you through the deployment of two Spring Boot microservices, namely "order-service" and "inventory-service," on Kubernetes using "MiniKube" . We will establish communication between them, with "order-service" making calls to an endpoint in "inventory-service." Additionally, we will configure "order-service" to be accessible from the local machine's browser . 1) Create Spring Boot microservices The Spring Boot microservices, "order-service" and "inventory-service," have been developed and can be found in this GitHub repository. If you are interested in learning more about creating Spring Boot REST microservices, please refer to this or this (Reactive) link. 2) Build Docker Images The Docker images for both "order-service" and "inventory-service" have already been generated and deployed on DockerHub, as shown below. codeburps/order-service cod...

Circuit Breaker Pattern with Resilience4J in a Spring Boot Application

Read Also: Spring Cloud Circuit Breaker + Resilience4j Resilience4j is a lightweight fault tolerance library that draws inspiration from Netflix Hystrix but is specifically crafted for functional programming. The library offers higher-order functions, known as decorators , designed to augment any functional interface, lambda expression, or method reference with features such as Circuit Breaker, Rate Limiter, Retry, or Bulkhead . These functionalities can be seamlessly integrated within a project, class, or even applied to a single method. It's possible to layer multiple decorators on any functional interface, lambda expression, or method reference, allowing for versatile and customizable fault tolerance. While numerous annotation-based implementations exist online, this article focuses solely on the reactive approach using router predicates and router functions . How Circuit Breaker Pattern works? In general, a circuit breaker functions as an automatic electrical s...

How to create a basic Spring 6 project using Maven

Below is a step-by-step guide to creating a basic Spring project using Maven. 1) Create a Maven Project Use the following Maven command to create a new Maven project. mvn archetype:generate -DgroupId=com.tb -DartifactId=spring-demo -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false 2) Import in IntelliJ IDEA If you haven't already, open IntelliJ IDEA on your system. Go to "File" > "New" > "Project from Existing Sources..." . In the file dialog, navigate to the directory where your Maven project is located. Select the pom.xml file within the project directory and click "Open." 3) Update pom.xml In total, the application requires the below-mentioned dependencies: 4) Create Spring Configuration Create a Java configuration class that uses annotations to define your Spring beans and their dependencies. This class should be annotated with @Configuration . 5) Create the Main Application C...