Building a REST API using Node.js, Express, and MongoDB: A Step-by-Step Guide
In this tutorial, we will walk you through the process of creating a REST API using Node.js and Express. We will also utilize MongoDB as our database to store the data.
Introduction
Our goal is to develop a trip cost calculator app. Imagine you are going on a trip and want to keep track of your expenses, such as gasoline, hotels, food, tickets, etc. You want to have an app where you can add and archive each expense, allowing you to review your spending history. While we won’t cover the frontend development in this tutorial, we will focus on creating the API.
API Endpoints Overview
Let’s start by defining the endpoints for our API:
/trip
with thePOST
method: This endpoint will create a new trip with a specified name./trips
with theGET
method: This endpoint will list all the trips, ordered by creation date./expense
with thePOST
method: This endpoint will add a new expense to a specific trip./expenses
with theGET
method: This endpoint will retrieve all the expenses for a specific trip.
Setting up the Project
To begin, make sure you have Node.js installed on your system. Create a new folder for your project called “tripcost” and navigate to that folder in your terminal. Initialize the project using the command npm init -y
.
We’ll also need to install two packages: mongodb
and express
. Run the following command to install both packages:
1 | npm install mongodb express |
Next, create a new file called server.js
and import the necessary modules:
1 | const express = require("express"); |
Implementing the API Endpoints
Now, let’s add the stubs for the API endpoints:
1 | app.post("/trip", (req, res) => { |
Finally, start the server using the listen()
method:
1 | app.listen(3000, () => console.log("Server ready")); |
Adding a Trip
Let’s start by implementing the /trip
endpoint for creating a new trip:
1 | app.post("/trip", (req, res) => { |
First, we need to establish a connection to the MongoDB database. Add the following code before the /trip
endpoint implementation:
1 | let db, trips, expenses; |
Now, we can continue with the implementation of the /trip
endpoint:
1 | app.post("/trip", (req, res) => { |
Listing Trips
Next, we’ll implement the /trips
endpoint to retrieve the list of trips:
1 | app.get("/trips", (req, res) => { |
Adding an Expense
Let’s move on to implementing the /expense
endpoint for adding a new expense:
1 | app.post("/expense", (req, res) => { |
Listing Expenses
Lastly, let’s implement the /expenses
endpoint to retrieve the list of expenses for a specific trip:
1 | app.get("/expenses", (req, res) => { |
Conclusion
Congratulations! You have successfully built a REST API using Node.js, Express, and MongoDB. Now, you can create, retrieve, and manage trips and expenses in your app. Feel free to explore and expand upon this foundation to further develop your application.
Tags: Node.js, Express, MongoDB, REST API