Building a RESTful API with Node.js and MongoDB involves creating routes, handling HTTP methods, connecting to a MongoDB database, and performing CRUD (Create, Read, Update, Delete) operations. Below is a simple example using Express as the web framework and Mongoose as the MongoDB ODM (Object Data Modeling library). Before you begin, make sure you have Node.js, npm, and MongoDB installed.
-
Initialize Your Project:
mkdir node-mongo-api cd node-mongo-api npm init -y
-
Install Dependencies:
npm install express mongoose body-parser
-
express:
Web framework for handling HTTP requests. -
mongoose:
MongoDB ODM for modeling and interacting with the database. -
body-parser:
Middleware to parse request bodies.
-
-
Create
app.js
(orindex.js
):const express = require('express'); const mongoose = require('mongoose'); const bodyParser = require('body-parser'); const app = express(); const PORT = process.env.PORT || 3000; // Connect to MongoDB mongoose.connect('mongodb://localhost:27017/your-database-name', { useNewUrlParser: true, useUnifiedTopology: true, }); // Define a simple mongoose schema and model const ItemSchema = new mongoose.Schema({ name: String, description: String, }); const Item = mongoose.model('Item', ItemSchema); // Middleware for parsing JSON app.use(bodyParser.json()); // Routes app.get('/api/items', async (req, res) => { try { const items = await Item.find(); res.json(items); } catch (error) { console.error(error); res.status(500).json({ error: 'Internal Server Error' }); } }); app.post('/api/items', async (req, res) => { const { name, description } = req.body; const newItem = new Item({ name, description }); try { const savedItem = await newItem.save(); res.json(savedItem); } catch (error) { console.error(error); res.status(500).json({ error: 'Internal Server Error' }); } }); // Other CRUD routes (e.g., GET /api/items/:id, PUT /api/items/:id, DELETE /api/items/:id) // Start the server app.listen(PORT, () => { console.log(`Server is running on http://localhost:${PORT}`); });
-
Run Your Server:
node app.js
Now you have a basic RESTful API with endpoints for retrieving all items (GET /api/items
) and creating a new item (POST /api/items
). Extend the routes and add logic for updating and deleting items based on your application requirements. Also, consider implementing input validation and error handling for a production-ready API.