
This blog post provides a detailed tutorial on creating a RESTful CRUD API using Node.js, Express, and MongoDB. It covers the setup, coding, and testing of the API, including creating, reading, updating, and deleting data, as well as best practices for structuring the application.
In this tutorial, we will learn how to build a complete RESTful CRUD API from scratch using Node.js, Express, and MongoDB. This guide is designed for beginners who want to understand the basics of backend development and how to create a simple CRUD application.
Before we start, ensure you have the following installed on your machine:
npm init -y to create a package.json file.index.js. This will be the main file for our backend.npm install express. Then, set up a basic Express server in index.js:
const express = require('express');
const app = express();
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
node index.js and visit http://localhost:3000 in your browser to see if it’s running.npm install mongoose to install Mongoose, which will help us interact with MongoDB.index.js, add the following code to connect to your MongoDB database:
const mongoose = require('mongoose');
mongoose.connect('your_connection_string', { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('Connected to MongoDB'))
.catch(err => console.error('Could not connect to MongoDB', err));
models.models folder, create a file named product.js and define the product schema:
const mongoose = require('mongoose');
const productSchema = new mongoose.Schema({
name: { type: String, required: true },
quantity: { type: Number, default: 0 },
price: { type: Number, required: true },
image: { type: String, required: false },
}, { timestamps: true });
const Product = mongoose.model('Product', productSchema);
module.exports = Product;
routes and a file named productRoutes.js inside it.productRoutes.js, set up the route to create a product:
const express = require('express');
const router = express.Router();
const Product = require('../models/product');
router.post('/products', async (req, res) => {
const product = new Product(req.body);
try {
await product.save();
res.status(201).send(product);
} catch (error) {
res.status(400).send(error);
}
});
module.exports = router;
index.js, import and use the routes:
const productRoutes = require('./routes/productRoutes');
app.use(express.json()); // Middleware to parse JSON
app.use('/api', productRoutes);
productRoutes.js:
router.get('/products', async (req, res) => {
try {
const products = await Product.find();
res.send(products);
} catch (error) {
res.status(500).send(error);
}
});
router.get('/products/:id', async (req, res) => {
try {
const product = await Product.findById(req.params.id);
if (!product) return res.status(404).send();
res.send(product);
} catch (error) {
res.status(500).send(error);
}
});
router.put('/products/:id', async (req, res) => {
try {
const product = await Product.findByIdAndUpdate(req.params.id, req.body, { new: true });
if (!product) return res.status(404).send();
res.send(product);
} catch (error) {
res.status(400).send(error);
}
});
router.delete('/products/:id', async (req, res) => {
try {
const product = await Product.findByIdAndDelete(req.params.id);
if (!product) return res.status(404).send();
res.send(product);
} catch (error) {
res.status(500).send(error);
}
});
To test the API, you can use tools like Postman or Insomnia. Here’s how to test each operation:
http://localhost:3000/api/products with a JSON body containing product details.http://localhost:3000/api/products to fetch all products or http://localhost:3000/api/products/:id for a specific product.http://localhost:3000/api/products/:id with updated product details.http://localhost:3000/api/products/:id to remove a product.In this tutorial, we built a complete CRUD API using Node.js, Express, and MongoDB. We covered the setup, coding, and testing of the API, including best practices for structuring the application. With this knowledge, you can now create your own backend applications and expand your skills in web development.
Paste a YouTube link and let Magica create the key takeaways.
Summarize another video