Building an API using Express.JS and MongoDB (Wishlist API Application)
Through the course of this read, our aim is to build and understand the implementation of a RESTful API using Express.js. By the end of this article, we will have built a basic Wishlist API. You can find all the code contained in this post over here.
Pre-requisites — Basics of JavaScript, little knowledge on Node.js, Express.js and Postman software.
Tools required — Node.js, NPM, Express.JS, mongoose, MongoDB, MongoDB Compass, Visual Studio Code (or Sublime Text) and Postman software.
SETTING UP THE ENVIRONMENT
1. Create your project directory at a desired location.
2. Open the folder in VS Code and open terminal and navigate to the created folder using the terminal (if you are using sublime text or any other editor, use windows CMD).
3. Inside terminal run following commands:
npm init -y
npm install mongoose express
npm install -D nodemon
Explanation of each command —
- npm init is used to initialize your node directory by creating a package.json file in the folder structure. The -y will initialize the package.json file to default values.
- npm install mongoose express will install the mongoose and express frameworks on node.
- npm install -D nodemon will install nodemon as a dev dependency (dev dependency means this package will not be deployed in production)
WHAT ARE WE USING AND WHY ARE WE USING:
Express.js — Express.js provides a robust set of features for web development and is the majorly used for creating RESTful APIs.
Mongoose — mongoose is a node framework which allows node/express to communicate with MongoDB.
Nodemon — nodemon is a dev tool which refreshes the node application each time a change is made in code files.
Postman — Postman is a software which tests our REST APIs.
FOLDER STRUCTURE FOR OUR PROJECT
db — db is the folder used for JavaScript files having MongoDB logic written.
models — models folder contains database schema for different collections.
Wishlist.js — Wishlist.js is a file which contains schema of Wishlist collection.
connection.js — JS file which is used to set up connection between express and MongoDB.
node_modules — all the directories you install using npm install command, they are stored in node_modules folder.
Index.js — file which contains our application logic.
Package.json — node configuration file.
BUILDING THE WISHLIST API:
STEP 1: SETTING UP THE DATABASE
Snippet above shows how to connect with a MongoDB database using mongoose library.
Mongoose provides a promise named “connect” which basically expects few parameters, first being the URL of the database (you can get that from MongoDB compass or from MongoDB CMD)
Second parameter is a object which basically sets some parameters to avoid depreciation warning. You can read about these warnings over here.
STEP 2: CREATING SCHEMA FOR WISHLIST
Here, we define the schema for our wishlist items. A Mongoose ‘schema’ is a document data structure (or shape of the document) that is enforced via the application layer.
For doing so, we create instance of mongoose.schema class and define the schema inside it. You can read all about mongoose schema over here.
STEP 3: WRITING LOGIC FOR OUR APIs
Step 1 and 2 were related to some database stuff. Now, let’s start with our main task which is handling API’s.
In this article we will handle four types of API method, which are GET, POST, PUT/PATCH, DELETE.
Before coding these method, we need to set some things up.
const express = require("express");
require("./db/connection");
const Wishlist = require("./db/models/Wishlist")
const app = express();
const port = process.env.PORT || 3000;
app.use(express.json());
To explain each line from above, first we have imported the express module in this file as here we are going to handle our API calls.
Second line imports our database which sets up the database connection. In third line we have created the Wishlist object from schema. Fourth line create an ‘app’ object from express. Fifth we have set our port variable. On the Sixth line, we have defined that our express application will use JSON objects (If you remove this line, express will not be able to identify JSON object).
POST
The first method is POST. Post method is used to send data from client to API server. In our case, we will use POST method to send data to server and insert a document in our database.
As I said, express is widely used for designing APIs, we already have predefined method such as “POST”. We can directly use this method to post our data.
Each API method in express expects two parameters, first is the URL on which the API method will be called and second is a callback function which defines what operation will be performed when this URL is hit. This callback function takes two parameters which are request and response objects.
In the snippet above, we want to insert document to our database, so will directly use the wishlist schema which we have designed and we will pass the request body (which will be a JSON object in our case) to it. schema.save() function will insert the document and commit to the database.
GET
The second method which we will use is the GET method. GET requests are made in order to retrieve data from server.
As shown in above snippet, we have used the “find()” method of mongoose which fetches all the documents from the database and returns them in the form of JSON object. You can read more about this method over here. With find method we have another method named “findById()” which returns the record based on the ID provided. You can read about this method over here.
PUT/PATCH
After GET and POST method, which are basically fetching and putting documents in database, next comes methods related to database update.
There are two API requests made for updating a record on server, namely PUT and PATCH.
The PUT request is used to update or create a new source. The PATCH method is used to partially update a source of data. The difference between PUT and PATCH is, PUT will update the whole data source, whereas PATCH only updates the required part of the data source.
Mongoose provides a method “findByIdAndUpdate()” using which we can find a document by it’s ID and update it. You can read more about it over here.
DELETE
The fourth API which we will see is DELETE API, which is used to delete resources.
Mongoose provides a method “findByIdAndDelete()” using which we can find a document by it’s ID and delete it. You can read more about this method over here.
TESTING WISHLIST API
Step 1: Start your express sever by following command:
nodemon index.js
Step 2: Open Postman software and add a new collection.
- From the three horizontal dots (basically stand for more actions :P), click on add request and create a request for POST.
Enter your express server URL proceeding with the extension you have used (“SaveWishlist” in my case), go to Body tab choose ‘raw’ from the radio button and select formatting as JSON and type your JSON object. Then hit the Send button.
Refresh your database on MongoDBCompass and check if document is inserted.
2. Just like we create a request for POST, create one for GET, enter the URL and hit the Send button.
3. Create a request for PATCH, enter URL with ID which needs to be updated, populate request body as we did for POST request and hit send and cross verify your results.
4. Create a request for DELETE, enter with URL and ID which needs to be deleted, and hit the Send button.
Hence, we have built an API to create, update and delete wishs using Express.js and MongoDB. This wishlist API is merely a simple API capable of performing database CRUD operations.
And that’s it! Did this work for you? Please leave any questions and comments below!
Thank you for reading!
If you found this article helpful, clap! 👏👏👏.