Building RESTful APIs with Node.js, Express & MongoDB
- 4.6/5
- 2157
- Aug 20, 2024
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