
How to make your first Rest API with Nodejs and MongoDb
Creating an API locally using Node.js is a great way to get started with backend development. Node.js is a powerful runtime environment that allows you to execute JavaScript code on the server side. In this blog, we'll walk through the steps to create a simple API using Node.js, Express.js (a popular web framework for Node.js), and MongoDB (a NoSQL database).
Prerequisites
Before we begin, make sure you have the following installed on your machine:
Node.js: You can download it from the official website.
npm (Node Package Manager): It comes bundled with Node.js.
Step 1: Set Up Your Project
Create a new directory for your project
mkdir my-first-api
cd my-first-api
Initialize a new Node.js project
npm init -y
Install Express.js
npm install express
Step 2: Create the Basic Server
Create a file named
index.js
in your project directory.Set up a basic Express server in
index.js
const express = require('express');
const app = express();
const port = 3000;
app.use(express.json());
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
Run your server
node index.js
You should see the message Server is running on http://localhost:3000
in your terminal. Open your browser and navigate to http://localhost:3000
to see the "Hello World!" message
Step 3: Create Your First Route
Let's create a simple route to handle CRUD (Create, Read, Update, Delete) operations for a resource, such as "users".
Add the following code to
index.js
let users = [
{ id: 1, name: 'John Doe' },
{ id: 2, name: 'Jane Smith' }
];
// Get all users
app.get('/users', (req, res) => {
res.json(users);
});
// Get a single user by ID
app.get('/users/:id', (req, res) => {
const user = users.find(u => u.id === parseInt(req.params.id));
if (!user) return res.status(404).send('User not found.');
res.json(user);
});
// Create a new user
app.post('/users', (req, res) => {
const newUser = {
id: users.length + 1,
name: req.body.name
};
users.push(newUser);
res.status(201).json(newUser);
});
// Update a user
app.put('/users/:id', (req, res) => {
const user = users.find(u => u.id === parseInt(req.params.id));
if (!user) return res.status(404).send('User not found.');
user.name = req.body.name;
res.json(user);
});
// Delete a user
app.delete('/users/:id', (req, res) => {
const userIndex = users.findIndex(u => u.id === parseInt(req.params.id));
if (userIndex === -1) return res.status(404).send('User not found.');
users.splice(userIndex, 1);
res.status(204).send();
});
Step 4: Organize Your Code
As your API grows, it's a good practice to organize your code into separate modules.
Create a directory named
routes
and a file namedusers.js
inside it.Move the user-related routes to
routes/users.js
const express = require('express');
const router = express.Router();
let users = [
{ id: 1, name: 'John Doe' },
{ id: 2, name: 'Jane Smith' }
];
// Get all users
router.get('/', (req, res) => {
res.json(users);
});
// Get a single user by ID
router.get('/:id', (req, res) => {
const user = users.find(u => u.id === parseInt(req.params.id));
if (!user) return res.status(404).send('User not found.');
res.json(user);
});
// Create a new user
router.post('/', (req, res) => {
const newUser = {
id: users.length + 1,
name: req.body.name
};
users.push(newUser);
res.status(201).json(newUser);
});
// Update a user
router.put('/:id', (req, res) => {
const user = users.find(u => u.id === parseInt(req.params.id));
if (!user) return res.status(404).send('User not found.');
user.name = req.body.name;
res.json(user);
});
// Delete a user
router.delete('/:id', (req, res) => {
const userIndex = users.findIndex(u => u.id === parseInt(req.params.id));
if (userIndex === -1) return res.status(404).send('User not found.');
users.splice(userIndex, 1);
res.status(204).send();
});
module.exports = router;
Update
index.js
to use the new route module
const express = require('express');
const app = express();
const port = 3000;
const userRoutes = require('./routes/users');
app.use(express.json());
app.use('/users', userRoutes);
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
Step 5: Connect to a Database
For a real-world application, you'll want to store your data in a database. You can use databases like MongoDB, MySQL, or PostgreSQL. For simplicity, let's use MongoDB with Mongoose, an ODM (Object Data Modeling) library for MongoDB and Node.js.
Install Mongoose
npm install mongoose
Create a file named
models/user.js
to define the User schema
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
name: { type: String, required: true }
});
const User = mongoose.model('User', userSchema);
module.exports = User;
Update
routes/users.js
to use Mongoose
const express = require('express');
const router = express.Router();
const User = require('../models/user');
// Get all users
router.get('/', async (req, res) => {
const users = await User.find();
res.json(users);
});
// Get a single 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.json(user);
});
// Create a new user
router.post('/', async (req, res) => {
const newUser = new User({ name: req.body.name });
await newUser.save();
res.status(201).json(newUser);
});
// Update a user
router.put('/:id', async (req, res) => {
const user = await User.findByIdAndUpdate(req.params.id, { name: req.body.name }, { new: true });
if (!user) return res.status(404).send('User not found.');
res.json(user);
});
// Delete a user
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(204).send();
});
module.exports = router;
Update
index.js
to connect to MongoDB
const express = require('express');
const mongoose = require('mongoose');
const app = express();
const port = 3000;
const userRoutes = require('./routes/users');
app.use(express.json());
app.use('/users', userRoutes);
mongoose.connect('mongodb://localhost:27017/mydatabase', { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log('MongoDB connected'))
.catch(err => console.log(err));
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
Conclusion
Congratulations! You've created your first REST API in Node.js using Express.js and connected it to a MongoDB database. This is a foundational step in building scalable and efficient web services. From here, you can expand your API by adding more routes, implementing authentication, and optimizing performance.
Want to learn more?
Join our community of developers and stay updated with the latest trends and best practices.
Comments
Please sign in to leave a comment.