Have you ever wondered how web applications communicate and exchange data? One common way is through RESTful APIs, which follow the principles of Representational State Transfer (REST). RESTful APIs allow clients to access and modify data using standard HTTP methods like GET, POST, PUT, and DELETE.
In this blog post, I’ll show you how to build a simple and scalable RESTful API with Node.js and Express. Node.js is a JavaScript runtime environment for fast and scalable server-side applications, and Express is a popular web framework for building web applications and APIs.
We’ll use MongoDB as our database and Mongoose as our object data modeling (ODM) library. We’ll also use Postman, a tool for testing and debugging APIs.
By the end of this blog post, you’ll be able to create your RESTful API with Node.js and Express.
Before we start, we need to have the following tools installed on our system:
• Node.js (version 14 or higher)
• MongoDB (version 4 or higher)
• Postman (version 8 or higher)
We also need to have some basic knowledge of JavaScript, Node.js, Express, MongoDB,
and Mongoose. If you are new to these technologies, you can check out the following
resources:
• JavaScript tutorial by MDN
• Node.js tutorial by nodejs.dev
• Express tutorial by Express
• MongoDB tutorial by MongoDB
• Mongoose tutorial by Mongoose
1. Create a Project Folder and Initialize
mkdir node-express-api
cd node-express-API
npm init -y
2. Install Dependencies:
npm install express mongoose nodemon
3. Update package.json
Scripts:
“start”: “nodemon index.js”
This setup initializes the project, installs necessary dependencies, and configures a script to run the server with Nodemon.
1. Create index.js
:
const express = require(‘express’);
const app = express();
const port = 3000;
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});
2. Run the Server:
npm start
This code imports Express, creates an Express app, defines a port, and starts the server. Running npm start
should show “Server running on port 3000” in the terminal. Routes will be defined next.
Add the following code to index.js
before defining routes:
const mongoose = require(‘mongoose’);
const connectionString = ‘mongodb://localhost:27017/node-express-api’;
mongoose.connect(connectionString, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
});
const db = mongoose.connection;
db.on(‘error’, console.error.bind(console, ‘connection error:’));
db.once(‘open’, () => {
console.log(‘Connected to the database’);
});
Create a file todo.js
:
const mongoose = require(‘mongoose’);
const todoSchema = new mongoose.Schema({
title: { type: String, required: true },
completed: { type: Boolean, default: false },
});
const Todo = mongoose.model(‘Todo’, todoSchema);
module.exports = Todo;
Update index.js
to include CRUD operations:
const express = require(‘express’);
const mongoose = require(‘mongoose’);
const Todo = require(‘./todo’);
const app = express();
const port = 3000;
app.use(express.json());
mongoose.connect(‘mongodb://localhost:27017/node-express-api’, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
});
const db = mongoose.connection;
db.on(‘error’, console.error.bind(console, ‘connection error:’));
db.once(‘open’, () => {
console.log(‘Connected to the database’);
});
app.get(‘/todos’, async (req, res) => {
try {
const todos = await Todo.find();
res.json(todos);
} catch (err) {
res.status(500).json({ message: err.message });
}
});
app.post(‘/todos’, async (req, res) => {
const { title, completed } = req.body;
try {
const todo = new Todo({
title,
completed,
});
const savedTodo = await todo.save();
res.status(201).json(savedTodo);
} catch (err) {
res.status(400).json({ message: err.message });
}
});
async function getTodoById(req, res, next) {
const id = req.params.id;
try {
const todo = await Todo.findById(id);
if (!todo) {
return res.status(404).json({ message: ‘Todo not found’ });
}
req.todo = todo;
next();
} catch (err) {
res.status(500).json({ message: err.message });
}
}
app.put(‘/todos/:id’, getTodoById, async (req, res) => {
const { title, completed } = req.body;
try {
req.todo.title = title;
req.todo.completed = completed;
const updatedTodo = await req.todo.save();
res.json(updatedTodo);
} catch (err) {
res.status(400).json({ message: err.message });
}
});
app.delete(‘/todos/:id’, getTodoById, async (req, res) => {
try {
await req.todo.remove();
res.status(204).json({ message: ‘Todo deleted’ });
} catch (err) {
res.status(500).json({ message: err.message });
}
});
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});
This completes the logic for our RESTful API. Now you can test it using Postman.
To test your RESTful API built with Node.js and Express using Postman, follow these steps:
Download and Install Postman:
Create a New Collection:
Create Requests:
Configure Requests:
http://localhost:3000/todos
).Content-Type
and value application/json
.{"title": "Learn Node.js", "completed": false}
).http://localhost:3000/todos/60f8f0a1d2d8c72f0c9e0b1c
).Send Requests:
Examples of Requests and Responses:
GET /todos
POST /todos
{
“title”: “Learn MongoDB”,
“completed”: false
}
DELETE /todos/