5 Simple Steps to Develop a RESTful API using Express.js and MongoDB

Tasadduq Ali
3 min readOct 5, 2023

--

Before we begin, Your support by clapping and leaving comments greatly influences my work. Additionally, if you’re interested in receiving a complimentary Full Stack Career consultation session every weekend, you can extend your support through PATREON.

Prerequisites

Before we dive into building the API, make sure you have the following prerequisites installed on your system:

  1. Node.js and npm (Node Package Manager): You can download and install them from nodejs.org.
  2. MongoDB: You’ll need a running instance of MongoDB. You can install it locally or use a cloud-based service like MongoDB Atlas.

Setting Up the Project

  1. Create a Project Directory: Start by creating a new directory for your project.
bashCopy code
mkdir my-restful-api
cd my-restful-api

2. Initialize a Node.js Project: Use the following command to create a package.json file for your project.

bashCopy code
npm init -y

3. Install Dependencies: Install Express.js and other necessary packages by running the following command:

bashCopy code
npm install express mongoose body-parser

Building the RESTful API

1. Setting Up Express.js

Create an app.js file in your project directory and set up Express.js:

javascriptCopy code
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');

const app = express();
const port = process.env.PORT || 3000;

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

// Connect to MongoDB
mongoose.connect('mongodb://localhost/my-restful-api', {
useNewUrlParser: true,
useUnifiedTopology: true,
});

// Define routes
app.use('/api', require('./routes/api'));

app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});

2. Defining Your Data Model

Create a models directory and define your data model using Mongoose. For example, let's create a simple Task model:

javascriptCopy code
const mongoose = require('mongoose');

const taskSchema = new mongoose.Schema({
title: String,
description: String,
completed: Boolean,
});

module.exports = mongoose.model('Task', taskSchema);

3. Creating Routes

Create a routes directory and define your API routes. Here's an example of CRUD operations on tasks:

javascriptCopy code
const express = require('express');
const router = express.Router();
const Task = require('../models/task');

// Create a new task
router.post('/tasks', async (req, res) => {
try {
const task = new Task(req.body);
await task.save();
res.status(201).send(task);
} catch (error) {
res.status(400).send(error);
}
});

// Get all tasks
router.get('/tasks', async (req, res) => {
try {
const tasks = await Task.find();
res.send(tasks);
} catch (error) {
res.status(500).send(error);
}
});



module.exports = router;

4. Testing the API

You can now start your Express.js server using node app.js. Your RESTful API should be accessible at http://localhost:3000/api.

To test your API, you can use tools like Postman or make HTTP requests using a tool like curl or a web client library like axios in your front-end application.

if you have any questions or suggestions just do let me know on my Instagram or at codeculturepro@gmail.com

--

--

Tasadduq Ali

I am MERN Stack developer working in UAE Govt to digitize their massive services. I will help you to become highly skilled Coder 😉