Introduction

In this guide, we'll walk you through the process of building a simple RESTful API using Node.js, Express, and MongoDB. You'll learn how to set up a basic API, perform CRUD (Create, Read, Update, Delete) operations, and interact with a MongoDB database. We'll provide code examples to help you get started.


Prerequisites

Before you begin, make sure you have the following prerequisites:

  • Node.js installed on your system. You can download it from nodejs.org.
  • MongoDB installed and running locally or accessible through a connection string.
  • A code editor or integrated development environment (IDE) for writing and running Node.js applications.

Step 1: Setting Up Your Project

Start by creating a new directory for your API project. Open your terminal and run the following commands:

mkdir my-restful-api
cd my-restful-api
npm init -y

This will create a new Node.js project with a

package.json
file.


Step 2: Installing Dependencies

Next, install the required Node.js packages for building the API. Run the following command:

npm install express mongoose

This installs the

express
framework for building the API and
mongoose
for MongoDB integration.


Step 3: Creating the API

Create a new file (e.g.,

app.js
) for your API and add the following code:

const express = require('express');
const mongoose = require('mongoose');
const app = express();
const port = 3000;
// Connect to your MongoDB database
mongoose.connect('mongodb://localhost/mydb', {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => {
console.log('Connected to MongoDB');
})
.catch((err) => {
console.error('Error connecting to MongoDB:', err);
});
// Define a schema and model for your data
const itemSchema = new mongoose.Schema({
name: String
});
const Item = mongoose.model('Item', itemSchema);
app.use(express.json());
// Define your API routes
// Create a new item
app.post('/items', async (req, res) => {
const newItem = new Item({
name: req.body.name
});
await newItem.save();
res.json(newItem);
});
// Get all items
app.get('/items', async (req, res) => {
const items = await Item.find();
res.json(items);
});
// Start the server
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});

Step 4: Running Your API

To run your API, use the following command:

node app.js

Your API will start, and you can access it at

http://localhost:3000
. You can use tools like Postman to interact with your API and perform CRUD operations.


Conclusion

You've successfully built a simple RESTful API using Node.js, Express, and MongoDB. You can expand and enhance this API to include additional routes, authentication, and more complex data models. This is just the beginning of your journey to creating powerful web services with Node.js and MongoDB.