Create API Endpoints for REST API in Node.js

Part 2. Making API endpoints to post or retrieve data

Umang Agrawal
JavaScript in Plain English

--

In this article you will get to know how endpoints are made to do CRUD (Create, Read, Update, Delete) operation on data stored on MongoDB Atlas database using Rest-API.

In the above article we saw how to setup the Node.js project and connect our MongoDB database to the Node.js. Now we will start with making api endpoints.

1. Firstly we have to make schema of the type of data that we want in our API, we will make the schema for products in the shop

Make a folder in the main directory names models and make a file named Products.js and the following code.

const mongoose = require('mongoose') // required to make the schemaconst ProductSchema = mongoose.Schema({
name: {
type: String,
required: true
},
price: {
type: Number,
required: true,
},
})
// we are exporting our schema for table Products.
module.exports = mongoose.model('Products', ProductSchema)

2. We have to define the routes to retrieve the data and post the data

Make a folder names routes in the main directory and then make a file named product.js.

Go to app.js in main dir and write the entry code for product route as following before the mongodb connection code:

// making the /products route for our productconst ProductRoute = require('./Routes/Product');
app.use('/products', ProductRoute)

Go to the product.js file in routes folder to start making get and post route as described below:

// we are making express router to handle different kinds of request like get/post/patch/deleteconst express = require('express')
const router = express.Router()
// We will me making this file in next step which will handle all our logic const ProductController = require('../controllers/product')// All these routes are there for our products like this:
// (http://localhost:5000/products/get) for getting all product
// (
http://localhost:5000/products/post) for posting a product
router.get('/get', ProductController.get_all_product);router.post('/post',ProductController.create_product)router.get('/:productId', ProductController.get_single_product)router.patch('/:productId',ProductController.patch_product_details)router.delete('/:productId',ProductController.delete_product)module.exports = router

3. Making the controller to handle all the logic behind the routes

Go to main directory of project and make folder named controller and make a file inside it named product.js

Now in this file all the logic behind the route will be there as below

For /get request:

// schema of the product table
const Product = require('../models/Product')
// Logic for the get request to get all the products
exports.get_all_product = async (req, res) => {
try {
// finding all the product in the table
const products = await Product.find()
// To check in the console
console.log(products)
res.send(products)
}catch (err) {
res.send({ message: err })
}
}
// Logic for the get request to get the single productexports.get_single_product = (req, res) => {
const id = req.params.productId; //get the productid from params
Product.findById(id)
.then(result => {
res.send(result) // if product is found then returned
})
.catch(err => {
res.send({message: err}) //gives error if product not found
})
}

for /post request

exports.create_product = async (req, res) => {
console.log(req.file)

// retrieving data from json body of post request
const product = new Product({
name: req.body.name,
price: req.body.price,
});
product.save()
.then(result => {
res.status(200).send({
_id: result._id,
name: result.name,
price: result.price,
request: {
type: 'GET',
url: 'http://localhost:5000/products/' + result._id
}
})
})
.catch(err => {
res.send({ message: err })
})
}

for /patch request

exports.patch_product_details = (req, res) => {
const id = req.params.productId; // get product ID from params
const update = {}
// checks for the value to be updated in item
for (const ops of req.body) {
update[ops.propName] = ops.value;
}
Product.update({ _id: id }, { $set: update })
.exec()
.then(result => {
res.send(result)
})
.catch(err => {
res.send(err)
})
}

for /delete request

exports.delete_product = (req, res) => {
const id = req.params.productId; //checks for productId to delete
Product.remove({ _id: id }) // removes product from table
.exec()
.then(result => {
res.send(result) //sends the result back
})
.catch(err => {
res.send(err) // sends error if product is not updated
})
}

We have completed all the routes and logic that is needed for the API to work, you can check your API by trying in any API testing tools like Postman.

Missed Part 1? Check it out below

Stuck with an error? No problem! Leave a comment and I will definitely try to solve it.

More content at plainenglish.io

--

--