In this tutorial you will learn how to create a RESTful API using node.js, express, and mongoDB.
This tutorial is made as simple as possible and easy to understand, even if you are a beginner in express and MongoDB.
Let's get started.
Step #1. EndPoint
This is important!
Before creating a RESTful API, it's a good idea to first define the EndPoint of the RESTful API that will be created.
EndPoint is the routes of the API that we will create.
RESTful API using HTTP verbs.
Commonly used HTTP verbs are GET, POST, PUT, PATCH, and DELETE.
GET to get data from the server or better known as READ, POST to CREATE new data, PUT or PATCH to UPDATE data, and DELETE to delete data.
Or better known as CRUD (Create-Read-Update-Delete).
In this tutorial, I will share how to create a simple RESTful API to retrieve data from the server (GET), create new data to the server (POST), update data to the server (PATCH), and delete data to the server (DELETE) from a collection in the database that is “Products”.
Here's the EndPoint design of the RESTful API we'll be making:
Step #2. Install Express, Mongoose, Nodemon, and Cors
Create a folder on your computer, here I name it “restful”.
If you create a folder with the same name, that's even better.
You are free to create it anywhere, whether in C, D, or on the Desktop.
Then open the "restful" folder using the code editor, here I use “Visual Studio Code”.
I also suggest you to use “Visual Studio Code”.
You can download Visual Studio Code at the following link and install it on your computer:
https://code.visualstudio.com/
Next, open a terminal in Visual Studio Code on the menu bar terminal => new terminal.
After that, type the following command in the terminal to create a “package.json” file:
npm init –y
Next, install express, mongoose, and cors by typing the following command in the terminal:
npm install express mongoose cors
Next, install nodemon as a development dependency by typing the following command in the terminal:
npm install –save-dev nodemon
Next, add the following code to the “package.json” file:
"type": "module",
So the file "package.json" looks like the following:
{ "name": "restful", "version": "1.0.0", "description": "", "type": "module", "main": "index.js", "scripts": { "test": "echo "Error: no test specified" && exit 1" }, "keywords": [], "author": "", "license": "ISC", "dependencies": { "cors": "^2.8.5", "express": "^4.17.1", "mongoose": "^5.12.14" }, "devDependencies": { "nodemon": "^2.0.7" } }
This is so that we can use ES6 Module Syntax to export and import modules.
Step #3. Index.js and Connect to Database
Create a file named “index.js” in the “restful” folder, then type the following code:
//import express import express from "express"; //import mongoose import mongoose from "mongoose"; // import routes import route from "./routes/index.js"; //import cors import cors from "cors"; // express function const app = express(); // connect to mongoDB database mongoose.connect("mongodb://localhost:27017/restful_db",{ useNewUrlParser: true, useUnifiedTopology: true }); const db = mongoose.connection; db.on('error', (error)=> console.error(error)); db.once('open', () => console.log('Database Connected')); // middleware app.use(cors()); app.use(express.json()); app.use('/product',route); // listening to port app.listen('3000',()=> console.log('Server Running at port: 3000'));
In the code above, I connect to the database "restful_db".
You don't need to create a “restful_db” database, mongoDB will create it automatically for you.
If you haven't installed mongoDB on your computer, please go to the official site: https://mongodb.com, then download the Community Server version of mongoDB by visiting the following link:
https://www.mongodb.com/try/download/community
Step #4. Routes
Create a folder named “routes”, then create a file named “index.js” in that folder.
Like the following picture:
Then type the following code in the "index.js" file contained in the "restful/routes" folder:
// import express import express from "express"; // import controllers import { getProducts, getProductById, saveProduct, updateProduct, deleteProduct } from "../controllers/productController.js"; // express router const router = express.Router(); // get All Products router.get('/', getProducts); // get single Product router.get('/:id', getProductById); // CREATE Product router.post('/', saveProduct); // UPDATE Product router.patch('/:id', updateProduct); // DELETE Product router.delete('/:id', deleteProduct); // export router export default router;
Step #5. Models
Create a folder named “models”, then create a file named “Product.js” in that folder.
Like the following picture:
Then type the following code in the "Product.js" file contained in the "restful/models" folder:
// import mongoose import mongoose from "mongoose"; // Create a Schema const Product = mongoose.Schema({ title:{ type: String, required: true }, price:{ type: Number, required: true } }); // export model export default mongoose.model('Products', Product);
Step #6. Controllers
Create a folder called “controllers”, then create a file named “productController.js” in that folder.
Like the following picture:
Then type the following code in the "productController.js" file contained in the "restful/controllers" folder:
// import model import Product from "../models/Product.js"; // get All Products export const getProducts = async (req, res) => { try { const products = await Product.find(); res.json(products); } catch (error) { res.status(500).json({message: error.message}); } } // get single Product export const getProductById = async (req, res) => { try { const product = await Product.findById(req.params.id); res.json(product); } catch (error) { res.status(404).json({message: error.message}); } } // Create a Product export const saveProduct = async (req, res) => { const product = new Product(req.body); try { const savedProduct = await product.save(); res.status(201).json(savedProduct); } catch (error) { res.status(400).json({message: error.message}); } } // Update a Product export const updateProduct = async (req, res) => { const product = await Product.findById(req.params.id); if(!product) return res.status(404).json({message: "No Data Found"}); try { const updatedProduct = await Product.updateOne({_id: req.params.id}, {$set: req.body}); res.status(200).json(updatedProduct); } catch (error) { res.status(400).json({message: error.message}); } } // Delete a Product export const deleteProduct = async (req, res) => { const product = await Product.findById(req.params.id); if(!product) return res.status(404).json({message: "No Data Found"}); try { const deletedProduct = await Product.deleteOne({_id: req.params.id}); res.status(200).json(deletedProduct); } catch (error) { res.status(400).json({message: error.message}); } }
Step #7. Testing
Run the application by typing the following command in the terminal:
nodemon index
Then, to do the test, you can use POSTMAN.
You can download POSTMAN at the following link then install it on your computer komputer:
https://www.postman.com/downloads/
After POSTMAN is installed on your computer, then run POSTMAN.
#7.1. POST a Product (CREATE)
Open POSTMAN, then select the "POST" method => Enter EndPoint in the URL field => select Body => raw => application/json => input data in json format => click Send button.
Like the following picture:
If successful, then there will be data as a response as shown above.
After that, insert some more data to make testing easier.
#7.2. GET All Products (READ)
Change the method to "GET" with the same EndPoint, then click the "Send" button.
Like the following picture:
To display products based on _id, add id in the URL field as shown below:
In the image above, I display the product with _id=60d16609546fa82a4c5d63e5.
#7.3. PATCH a Product (UPDATE)
Select the "PATCH" method => Enter the EndPoint along with the _id of the product to be updated in the URL column => select Body => raw => application/json => input data in json format => click the Send button.
Like the following picture:
If the update is successful, there will be "nModified": 1 as shown above.
#7.4. DELETE a Product (DELETE)
Select the "DELETE" method, then enter the URL along with the _id to be deleted, then click the "Send" button.
Like the following picture:
If the delete is successful, there will be a "deletedCount": 1 as shown above.
In the picture above, I deleted the product with _id=60d16609546fa82a4c5d63e5.
Conclusion:
Today's discussion is how to create a RESTful API using node.js, express, and mongoDB.
Not only that, you've also learned how to structure your application into sections: models, controllers, and routes.
So what are you waiting for, Let's Coding!
Download Source Code
Comments (0)