Creating Custom APIs with MongoDB
Introduction
Custom APIs allow you to build specific functionalities and endpoints tailored to your application's needs. This tutorial will guide you through the steps to create a custom API using MongoDB, Node.js, and Express.js.
Setting Up
To get started, you need to set up a Node.js project and install the necessary dependencies:
Setting Up the Project
mkdir custom-api cd custom-api npm init -y npm install express mongoose body-parser
Connecting to MongoDB
Create a db.js
file to handle the connection to MongoDB:
db.js
const mongoose = require('mongoose'); const connectDB = async () => { await mongoose.connect('mongodb://localhost:27017/customapi', { useNewUrlParser: true, useUnifiedTopology: true, }); console.log('MongoDB connected'); }; module.exports = connectDB;
Creating the User Model
Create a models/User.js
file to define the MongoDB schema and model:
User.js
const mongoose = require('mongoose'); const userSchema = new mongoose.Schema({ name: String, email: String, }); module.exports = mongoose.model('User', userSchema);
Creating Express Routes
Create a routes/user.js
file to define the API endpoints for user operations:
user.js
const express = require('express'); const router = express.Router(); const User = require('../models/User'); // Create a new user router.post('/', async (req, res) => { const user = new User(req.body); await user.save(); res.status(201).send(user); }); // Get all users router.get('/', async (req, res) => { const users = await User.find(); res.status(200).send(users); }); // Get a user by ID router.get('/:id', async (req, res) => { const user = await User.findById(req.params.id); if (!user) return res.status(404).send('User not found'); res.status(200).send(user); }); // Update a user by ID router.put('/:id', async (req, res) => { const user = await User.findByIdAndUpdate(req.params.id, req.body, { new: true, runValidators: true }); if (!user) return res.status(404).send('User not found'); res.status(200).send(user); }); // Delete a user by ID router.delete('/:id', async (req, res) => { const user = await User.findByIdAndDelete(req.params.id); if (!user) return res.status(404).send('User not found'); res.status(200).send('User deleted'); }); module.exports = router;
Setting Up Express Server
Create an index.js
file to set up the Express server and connect everything together:
index.js
const express = require('express'); const bodyParser = require('body-parser'); const connectDB = require('./db'); const userRoutes = require('./routes/user'); const app = express(); connectDB(); app.use(bodyParser.json()); app.use('/api/users', userRoutes); const port = process.env.PORT || 3000; app.listen(port, () => { console.log(`Server running on port ${port}`); });
Running the Server
Start the server by running the following command:
Starting the Server
node index.js
You should see the message "Server running on port 3000" indicating that the Express server is running.
Testing the API
Use tools like Postman or curl to test the API endpoints. Here are some example requests:
Example: Creating a User
curl -X POST http://localhost:3000/api/users -H "Content-Type: application/json" -d '{"name":"John Doe","email":"john.doe@example.com"}'
Example: Getting All Users
curl http://localhost:3000/api/users
Conclusion
In this tutorial, you have learned how to create a custom API with MongoDB using Node.js and Express.js. This setup allows you to build flexible and powerful APIs for interacting with your MongoDB data.