How to Build a REST API with CRUD Functionalities Using Express.js, Node.js, and connect to MongoDB (Beginner's Guide)
Learn How to Create, Read, Update, and Delete Data Using Express.js and MongoDB.
Table of contents
- Introduction.
- Requirements.
- Getting Started.
- Step 1: Setting up your folders.
- Step 2: Installing our packages and dependencies.
- Step 3: Configuring our connections.
- Step 4: Creating a MongoDB account and database.
- Step 5: Connecting to our mongoDB database.
- Step 6: Building our API with CRUD operations.
- Step 7: Testing our API with POSTMAN.
- Conclusion
Introduction.
Hello there, I’m Raphael. If you are a beginner web developer aspiring to learn backend web development with ease then you are in the right place. I have compiled a super easy step by step tutorial on the most important skill a backend developer must and should learn - How to build a REST API with a Create, Read, Update and Delete functionality as well as how to easily create a MongoDB database and connect using Mongoose.
Don’t worry, I have taken a good load of time to make sure that you understand each step by using simple sentences along with my screenshot image that shows you the processes involved so that you can easily practice along by yourself. It will be like taking a work in the park, I promise.
Without much ado, let’s begin.
What is REST API?
REST stands for Representational State Transfer. It’s just a fancy way of saying, "Hey, let’s use the internet to send and receive information in a simple and organized way.”
API stands for Application Programming Interface. It’s like a messenger that takes your request, goes to a server (a big computer that stores data), and brings back the information you asked for.
Think of a vending machine. You press a button (send a request) to ask for a bag of chips, the vending machine (REST API) checks if it has the chips, if it does, it gives you the chips (sends a response). If not, it says, "Sorry, no chips left".
In simple terms, a REST API is like a helper that takes your request, goes to a big computer (server), and brings back the information you need. It’s super useful because it makes apps smarter, faster, and able to talk to each other!
What we will be learning in this tutorial.
How to setup and configure our backend connections with Express.js and Node. (step 3)
How to create a MongoDB Atlas account and setup our database. (step 4)
How to connect our API to our Atlas database. (step 5)
How to build a REST API with CRUD operations (Create, Read, Update and Delete). (step 6)
We will be using Node.js (backend runtime), Express.js which is a framework for handling routes, MongoDB and Mongoose, a Database and ODM as well as Postman extension to test our endpoints.
Requirements.
As an aspiring backend developer, I assume you already have knowledge of frontend which includes a basic knowledge of JavaScript.
You must have Node.js and npm installed**.**
MongoDB installed or a MongoDB Atlas account for cloud database.
VS Code or any other code editor.
Postman extension (for testing the API).
Getting Started.
Step 1: Setting up your folders.
Create a folder on your desktop. You can name it anything you like, I’ll name mine “mern-tutorial”.
Open the created folder with any text editor of your choice, I’ll be using VS code.
In the folder, create another folder named backend, this is where we will have our routes controllers and models.
Step 2: Installing our packages and dependencies.
Open your Terminal, you can use your systems terminal or use the VS code terminal.
Type in the following command
npm init
this will ask you series of questions like description: type in any description you like, end point: we will use our server.js file as the entry point, keyword: skip by pressing enter, author: you may type in your name, license: skip to use the default. This command will create a package.json file on your root folder (main folder).Now let us install our dependencies by typing in the following command
npm i express dotenv mongoose
This will install express, mongoose and dotenv (we need to install dotenv when working with environment variables in Node.js projects. It allows us to load environment variables from a.env
file intoprocess.env
. Don’t worry, We will see how this works in later steps.We installed dotenv because we will be using a
.env
file. Now let use create this file in our root folder. We will be using it in later steps.When using Node.js we always need to restart our server when we make changes to any file which becomes a pain to bare. We will be using a package known as nodemon, with this package installed and setup, it automatically restarts the server for us so we don’t have to manually stop and start the server when ever we make changes to our file. in your terminal type in the following command
npm i -D nodemon
this installs nodemon as a dev dependency.- Now to setup nodemon, we will edit and add a script called “start” and “server”, so that nodemon will run our server.js file when we type in
npm run server
in our terminal. Type "start": "node backend/server.js", "server": "nodemon backend/server.js" mind your punctuations, we wouldn’t want to have our app not working cause we forgot to add a comma.
- Now to setup nodemon, we will edit and add a script called “start” and “server”, so that nodemon will run our server.js file when we type in
- Let us check if our nodemon is working fine. in your terminal type in
npm run server
If it shows the lines in the screenshot image below, then it is working.
one last setup before we continue, go to the root folder and create a file called
.gitignore
this file will contain files and folders names you do not want to include if you will push your projects to github.
Step 3: Configuring our connections.
Create a server.js file in the backend folder. Remember we will use this file as our main entry point.
Now let us bring in express.js and dotenv for our environment variables by coding in the server.js file. we attach a function
.config
to the dotenv to configure it
const express = require('express');
const dotenv = require('dotenv').config();
- create a port variable and put 5000 to it. this is the port our server will run on.
const port = 5000;
- Now, we initialize express by creating a variable called app and setting it to express
const app = express();
- On the app variable, we call an object “listen()” which takes in our port variable created above and then a second argument with an arrow function which we will log a text using template literal.
app.listen(port, () => console.log(`Server started on port ${port}`))
Time to use our
.env
file. We will make our port number an environment variable by adding it to the.env
file. Go to the.env
file and create a variable PORT (use capital letters) and set it to 5000- Now go back to your server.js file, edit the port variable to the following code below.
const port = process.env.PORT
The code above allows us to access the port variable in the
.env
fileNow let us check if our connections are working by starting the server. type
npm run server
in your terminalIf you have the result in the screenshot image below, then it is working just fine. Note that whenever you make changes to the
.env
file, you must always restart the server (ctrl or command c to stop the server then typenpm run server
to start again)
Step 4: Creating a MongoDB account and database.
- Visit the Official MongoDB website and create an account. I will be using MongoDB Atlas which is a cloud database. Click on product (screenshot image below)
- In “Build with MongoDB Atlas” section, click on sign up, and register an account (screenshot image below)
- After successfully creating your account, your page should look like this. (screenshot image below) You may skip the personalization questions.
Next, we create a cluster by clicking on the button (check screenshot image above)
On the page that will be shown, select the free plan (screenshot image below)
- You may leave every other options, scroll down and click on create deployment (screenshot image below)
- Creating your cluster for the first time might take a short while to setup so you would have to wait for about 3 to 5 minutes.
On the next page that pops up, you need to set up your connection security for your cluster account by:
Adding your connection IP address
Adding a name and password for your database, type in a username and a password you can remember then click on the “create database user” button
- After adding your IP address and a database user, your page should look like this(screenshot image below) and the “choose a connection method” button should be highlighted green.
- After clicking on the “choose a connection method” button highlighted green, the next section is where you choose a connection method. click on the “Drivers” under “Connect to your application” (see screenshot image below).
- this will take you to another page, skip the first 2 steps as we have already done them, scroll down to number 3 (the third step) “Add your connection string into your application code” copy the connection string (see screenshot image below)
- When you have copied your connection string, scroll down and click on the “done” button highlighted green.
Now, let us create our database.
- After your cluster is setup, your page should look like the screenshot image below which shows your cluster (the default name is “Cluster0”). on the overview section. Click on the “Browse collections” button.
- Under the collections section, click on the “Create database” button (screenshot image below)
- Type in your database name (you will be adding this name to your collection string). You do not necessarily need to add a collections name right away since we will not be adding and using a collection in the database in this tutorial (don’t be confused by what a collection is, if you are familiar with relational databases such as MySQL this is the same thing as a table with roles and columns, so relational databases use the term tables while NoSQLs like MongoDB use collections). You may skip the “Additional preferences” then click on the create button (screen shot image below)
- Your created database should look like this along with the collection (screenshot image below)
Well done. We have successfully created our MongoDB account and also setup our database. It wasn’t that hard was it? Okay, good. Let us go back to our editor and continue from where we stopped. Next up, connecting to our database.
Step 5: Connecting to our mongoDB database.
We now have a copy of our connection string. The next step is to use that connection string in our code.
Go to your
.env
file, paste the connection string you copied from your database, name it MONGO_URI (all in capital letters). Here’s a quick side note. copying your string for the first time right after creating your database will automatically have your username and password in it. After exiting your database account, the next time you log back in to copy them, you would need to manually type in the password in the string. Do not forget to restart your server since you added a new environment variable (always restart your server when ever you make changes to the.env
file.When you have pasted your connection string, you will need to add your database name in the string. Check screenshot image below. (The highlighted texts in red are texts you need to manually add to your string when creating a connection string).
Now go to your backend folder, create a folder named “config”. Inside the config folder, create a file named db.js. In the file, type in the codes in the screenshot image below. Don’t worry, I will use comments to explain what each line of code does.
- Next, go to your server.js file, import the connectDB function then call the function (screenshot image below)
You will see a message logged in your terminal showing that you have successfully connected to your Atlas database (screenshot image below)
A quick side note: If yours does not connect, maybe you see an error message on your terminal, go back to your account, click on the Network access on the left side and be sure to Add your current IP address.
Step 6: Building our API with CRUD operations.
- Before building our REST API, we need to create a model for our database, we will use this model in our API functions
In the backend folder, create a new folder called “model”
Inside the model folder, create an itemModel.js file. This is where we will define our mongoose schema (A schema is basically a blueprint or layout for how you want your data to be structured in a MongoDB database. It defines the fields, data types, and rules for documents in a collection or table). In this Schema, we will only be using a text field and a timestamp rule set to true. (see screenshot image below with comments that explains each line of code)
Next, import the schema file into your server.js file. We will now use our created schema in our API.
Quick side note. the imported schema file “Item” have some mongoose methods on it that we will use in our API. These methods include create(), find(), findById(), findByIdAndUpdate() and findByIdAndDelete().
- API to CREATE an item.
// This Handles HTTP POST requests to the "/api/items" endpoint
app.post("/api/items", async (req, res) => {
// Extracts the "text" property from the request body
const { text } = req.body;
// Let us checks if "text" is missing or empty
if (!text) {
// If it is then we sends a 400 (Bad Request) response with an error message
return res.status(400).json({ message: "Text is required" });
}
// Then we create a new item in the database with the provided text
const newItem = await Item.create({ text });
// And then send a 200 (OK) response with the newly created item as JSON
res.status(200).json(newItem);
});
- API to GET all items.
// This handles HTTP GET requests to the "/api/items" endpoint
app.get("/api/items", async (req, res) => {
// Then fetches all items from the database
const items = await Item.find();
// And sends a 200 (OK) response with the retrieved items as JSON
res.status(200).json(items);
});
- API to GET a single item.
// This will handle HTTP GET requests to "/api/items/:id" to get a specific item by its ID
app.get("/api/items/:id", async (req, res) => {
// This line finds an item in the database using the ID provided in the URL
const item = await Item.findById(req.params.id);
// Checks if the item exists
if (!item) {
// sets the response status to 404 if Not Found
res.status(404);
// Throws an error message (this assumes you have error handling middleware)
throw new Error("Item not found");
}
// Sends a 200 (OK) response with the retrieved item as JSON
res.status(200).json(item);
});
- API to UPDATE an item.
// This will handles HTTP PUT requests to "/api/items/:id" to update a specific item
app.put("/api/items/:id", async (req, res) => {
// Finds an item by ID and updates it with the new data from the request body
const updatedItem = await Item.findByIdAndUpdate(req.params.id, req.body, {
new: true, // Returns the updated item instead of the old one
});
// Checks if the item exists
if (!updatedItem) {
res.status(404);
throw new Error("Item not found");
}
// Sends a 200 (OK) response with the updated item as JSON
res.status(200).json(updatedItem);
});
- API to DELETE an item.
// This Handles HTTP DELETE requests to "/api/items/:id" to delete a specific item
app.delete("/api/items/:id", async (req, res) => {
// Finds an item by ID and deletes it from the database
const deletedItem = await Item.findByIdAndDelete(req.params.id);
// Checks if the item exists before deleting
if (!deletedItem) {
res.status(404);
throw new Error("Item not found");
}
// Sends a 200 (OK) response with a success message and the deleted item
res.status(200).json({
message: "Item deleted successfully",
});
});
Step 7: Testing our API with POSTMAN.
You can download the postman app from their website or use the extension in your code editor. I will be using the Postman VS code extension.
How to install and setup Postman extension in your code editor (VS Code)
To install.
Go to the extension section.
In the search bar, type in postman and install. (Be sure to install the original with a checkmark beside its name (screenshot image below).
To Setup
Click on the postman icon.
Click on the '“New HTTP Request” button.
Your postman is setup and ready to use (screenshot image below)
Let us start with the CREATE request.
In the request search bar, type in http://localhost:5000/api/items
click on Body
choose “x-www-form-urlencoded”
In key section, type “text”
In value section, type any text you want
Be sure the checkbox is checked.
Click and choose POST from the dropdown menu.
Click on Send button. (screenshot image below)
You will see your created text item with an Id (from MongoDB) and the timestamp (createdAt & updatedAt) that shows a statusCode of 200 which is okay.
Check your Atlas account database collection, you will see our created item in our database.
Let us create 2 more items and get all items in the next step.
Quick side note: For you to be able to send Form Data (x-www-form-urlencoded) from the body when you use the POST (to create) or PUT (to update) in POSTMAN, you need to add a middleware that allows your application to parse incoming form data (URL-encoded data) and add a key-value pair. Don’t worry, it’s just two lines of code. Go to your server.js file right above where you initialized express and type
// Middleware to parse JSON data from incoming requests (POST or PUT) from POSTMAN
app.use(express.json());
// Middleware to parse URL-encoded data from incoming requests (POST or PUT) from POSTMAN
app.use(express.urlencoded({ extended: false }));
This will allow us successfully send POST or PUT request with postman.
Next, the Get All Items request.
In the request search bar, type in http://localhost:5000/api/items
click and choose GET from the dropdown menu.
click on Send button. (screenshot image below).
This displays all available (created) text items in our database.
Next, the Get a single Item by Id request.
Let us get a specific item (My Third Created Item” by it’s Id.
In the request search bar, type in http://localhost:5000/api/items/67cdeb9ae18d914bdb77b596 (this is the id of the third text item).
click and choose GET from the dropdown menu.
click on Send button. (screenshot image below).
Next, the UPDATE request.
We will update the second text item (My Second Created Item) by its Id.
In the request search bar, type in http://localhost:5000/api/items/67cebb81f607269238e9a0fa (this is the Id of the Second text item)
click on Body
choose “x-www-form-urlencoded”
In key section, type “text”
In value section, type any text you want to update the current text.
Be sure the checkbox is checked.
Click and choose PUT from the dropdown menu.
Click on Send button.
Here’s what the current database look like in your postman (screenshot image below). You will also see the same thing when you check your Atlas database account.
The final step, testing our DELETE request
We will Delete the second text item (The text item we recently Updated) by its Id.
In the request search bar, type in http://localhost:5000/api/items/67cebb81f607269238e9a0fa (this is the Id of the Second text item).
Click and choose DELETE from the dropdown menu.
Click on Send button.
This deletes the item of the selected Id.
Click on the Apply button to refresh and apply your current data in your database (screenshot image below).
Conclusion
And just like that, you’ve built a fully functional REST API with Express.js, Node.js, and MongoDB. Not bad, right? You’ve officially joined the club of developers who talk to databases like they’re old friends.
Now, what’s next? Well, you can either sit back and admire your work (totally valid) or start adding more features, like authentication, validation, and maybe even some error messages that don’t sound like they’re screaming at your users.
Coding is a journey, and even the best developers started with “Why isn’t this working?!!!!” moments. So you have to keep building and keep learning. Enjoy the thrill of doing it. Trust me, it doesn’t get easier, you just get better.
Here’s a link to the projects Github Repo https://github.com/Raphael-Obasi/REST-API-CRUD-TUTORIAL