In this article, we will guide you through the process of building a RESTful API using Node.js, Express, and MongoDB. We will cover the basics of each technology, and then dive into the implementation details of building a fully functional API.
Introduction to Node.js, Express, and MongoDB
Node.js
Node.js is a JavaScript runtime built on Chrome’s V8 JavaScript engine. It allows developers to run JavaScript on the server-side, making it a popular choice for building scalable and high-performance web applications.
Express
Express is a popular Node.js web framework that provides a flexible and modular way to build web applications. It provides a robust set of features, including routing, middleware, and templating, making it an ideal choice for building RESTful APIs.
MongoDB
MongoDB is a NoSQL database that stores data in a JSON-like format, making it a natural fit for JavaScript-based applications. It provides a scalable and high-performance data storage solution, with features like document-based data model, dynamic schema, and rich querying capabilities.
Setting Up the Project
To start building our API, we need to set up a new Node.js project. Create a new directory for your project and navigate to it in your terminal. Run the following command to initialize a new Node.js project:
bash
npm init
Follow the prompts to create a package.json file.
Next, install the required dependencies:
bash
npm install express mongoose body-parser
Here, we’re installing Express, Mongoose (a MongoDB ORM for Node.js), and Body-Parser (a middleware for parsing JSON request bodies).
Creating the API
Create a new file called app.js and add the following code:
javascript
const express = require(‘express’);
const app = express();
const mongoose = require(‘mongoose’);
const bodyParser = require(‘body-parser’);
app.use(bodyParser.json());
mongoose.connect(‘mongodb://localhost/mydatabase’, { useNewUrlParser: true, useUnifiedTopology: true });
const db = mongoose.connection;
db.on(‘error’, (err) => {
console.error(err);
});
db.once(‘open’, () => {
console.log(‘Connected to MongoDB’);
});
app.get(‘/’, (req, res) => {
res.send(‘Welcome to my API’);
});
app.listen(3000, () => {
console.log(‘Server listening on port 3000’);
});
Here, we’re creating an Express app, connecting to a MongoDB database, and defining a simple route for the root URL (/).
Defining the API Endpoints
Let’s define some API endpoints for a simple todo list application. Create a new file called todo.model.js and add the following code:
javascript
const mongoose = require(‘mongoose’);
const todoSchema = new mongoose.Schema({
title: String,
completed: Boolean
});
const Todo = mongoose.model(‘Todo’, todoSchema);
module.exports = Todo;
Here, we’re defining a Mongoose model for our todo items.
Create a new file called todo.controller.js and add the following code:
javascript
const Todo = require(‘./todo.model’);
exports.getAllTodos = async (req, res) => {
const todos = await Todo.find();
res.json(todos);
};
exports.createTodo = async (req, res) => {
const todo = new Todo(req.body);
await todo.save();
res.json(todo);
};
exports.getTodoById = async (req, res) => {
const todo = await Todo.findById(req.params.id);
if (!todo) {
res.status(404).send(‘Todo not found’);
} else {
res.json(todo);
}
};
exports.updateTodo = async (req, res) => {
const todo = await Todo.findById(req.params.id);
if (!todo) {
res.status(404).send(‘Todo not found’);
} else {
todo.title = req.body.title;
todo.completed = req.body.completed;
await todo.save();
res.json(todo);
}
};
exports.deleteTodo = async (req, res) => {
const todo = await Todo.findById(req.params.id);
if (!todo) {
res.status(404).send(‘Todo not found’);
} else {
await todo.remove();
res.json({ message: ‘Todo deleted successfully’ });
}
};
Here, we’re defining controllers for our API endpoints.
Update the app.js file to include the API endpoints:
javascript
const express = require(‘express’);
const app = express();
const mongoose = require(‘mongoose’);
const bodyParser = require(‘body-parser’);
const todoController = require(‘./todo.controller’);
app.use(bodyParser.json());
mongoose.connect(‘mongodb://localhost/mydatabase’, { useNewUrlParser: true, useUnifiedTopology: true });
const db = mongoose.connection;
db.on(‘error’, (err) => {
console.error(err);
});
db.once(‘open’, () => {
console.log(‘Connected to MongoDB’);
});
app.get(‘/’, (req, res) => {
res.send(‘Welcome to my API’);
});
app.get(‘/todos’, todoController.getAllTodos);
app.post(‘/todos’, todoController.createTodo);
app.get(‘/todos/:id’, todoController.getTodoById);
app.put(‘/todos/:id’, todoController.updateTodo);
app.delete(‘/todos/:id’, todoController.deleteTodo);
app.listen(3000, () => {
console.log(‘Server listening on port 3000’);
});
Here, we’re including the API endpoints in our Express app.
Testing the API
Use a tool like Postman or cURL to test the API endpoints. You can also use a tool like MongoDB Compass to view the data in your MongoDB database.
Conclusion
In this article, we built a RESTful API using Node.js, Express, and MongoDB. We defined API endpoints for a simple todo list application and implemented controllers to handle the logic for each endpoint. We also connected to a MongoDB database and used Mongoose to interact with the data.
This is just the beginning of building a fully functional API. You can add more endpoints, implement authentication and authorization, and use other technologies like Redis or GraphQL to enhance the performance and scalability of your API.