CRUD operations (Create, Read, Update, Delete) are the fundamental building blocks of most web applications. In this tutorial, we’ll walk through the process of creating a simple CRUD API using Node.js, Express, and MongoDB — a powerful combination for building robust and scalable APIs.
Prerequisites:
Before we begin, make sure you have Node.js and MongoDB installed on your system. If not, you can download and install them from the official websites.
Step 1: Setting Up Your Project
1. Create a new directory for your project and navigate to it in your terminal.
2. Initialize a Node.js project using npm:
npm init -y
3. Install the required dependencies: Express and Mongoose (for MongoDB connectivity):
npm install express mongoose
4. Create an entry file (e.g., app.js
) to start building your API.
Step 2: Building the API Structure
In your app.js
file, set up the basic structure of your Express application:
const express = require('express');
const mongoose = require('mongoose');
const app = express();
const port = process.env.PORT || 3000;
// Middleware to parse JSON requests
app.use(express.json());
// Connect to MongoDB
mongoose.connect('mongodb://localhost/crud-api', {
useNewUrlParser: true,
useUnifiedTopology: true,
});
// Define a mongoose model and schema
const Todo = mongoose.model('Todo', {
title: String,
description: String,
});
// Routes go here
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
Step 3: Implementing CRUD Operations
Create (POST)
app.post('/todos', async (req, res) => {
try {
const todo = new Todo(req.body);
await todo.save();
res.status(201).send(todo);
} catch (error) {
res.status(400).send(error);
}
});
Read (GET)
app.get('/todos', async (req, res) => {
try {
const todos = await Todo.find();
res.send(todos);
} catch (error) {
res.status(500).send(error);
}
});
Update (PUT)
app.put('/todos/:id', async (req, res) => {
try {
const todo = await Todo.findByIdAndUpdate(req.params.id, req.body, { new: true });
if (!todo) {
return res.status(404).send();
}
res.send(todo);
} catch (error) {
res.status(400).send(error);
}
});
Delete (DELETE)
app.delete('/todos/:id', async (req, res) => {
try {
const todo = await Todo.findByIdAndDelete(req.params.id);
if (!todo) {
return res.status(404).send();
}
res.send(todo);
} catch (error) {
res.status(500).send(error);
}
});
Step 4: Testing Your CRUD API
You can use tools like Postman or cURL to test your API. Here are some sample requests:
Create a new todo (POST):
POST http://localhost:3000/todos
Content-Type: application/json
{
"title": "Learn Node.js",
"description": "Build amazing applications with Node.js"
}
Read all todos (GET):
GET http://localhost:3000/todos
Update a todo (PUT):
PUT http://localhost:3000/todos/:id
Content-Type: application/json
{
"title": "Learn Node.js and Express"
}
Delete a todo (DELETE):
DELETE http://localhost:3000/todos/:id
Conclusion:
Congratulations! You’ve created a simple CRUD API using Node.js and Express. This is just the beginning of building powerful and scalable web applications. You can expand upon this foundation by adding validation, authentication, and more advanced features to meet the needs of your specific project. Happy coding!