Creating a REST API with Node.js, Express.js, TypeScript, and MongoDB

rest api

Sharing is caring!

199 Views -

Developing a robust and scalable web application requires building a well-designed API. Representational State Transfer (REST) APIs have become the industry standard for communication between client applications and servers. In this tutorial, we will explore how to create a REST API using Node.js, Express.js, TypeScript, and MongoDB. This powerful combination offers enhanced productivity, maintainability, and flexibility for building modern web applications.

Prerequisites:

To follow along with this tutorial, you should have a basic understanding of JavaScript, Node.js, and TypeScript. Additionally, you will need Node.js and npm (Node Package Manager) installed on your system. You should also have a MongoDB instance set up or access to a MongoDB server.

Setting Up the Project:

Let’s begin by setting up our project and installing the necessary dependencies. Follow the steps below:

Step 1: Create a new directory for your project.

mkdir rest-api
cd rest-api

Step 2: Initialize a new Node.js project.

npm init -y

Step 3: Install the required dependencies.

npm install express mongoose body-parser typescript ts-node

Step 4: Initialize TypeScript configuration.

npx tsc --init

Building the API:

Now that our project is set up, let’s create an entry point file (e.g., index.ts) and start building our REST API.

Step 1: Import required modules and define types

import express, { Request, Response } from 'express';
import mongoose, { Schema, Document } from 'mongoose';

interface IUser extends Document {
  name: string;
  email: string;
  age: number;
}

const UserSchema = new Schema<IUser>({
  name: { type: String, required: true },
  email: { type: String, required: true },
  age: { type: Number, required: true },
});

const User = mongoose.model<IUser>('User', UserSchema);

Step 2: Configure the Express app and MongoDB connection.

const app = express();
const port = 3000;

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

mongoose.connect('mongodb://localhost:27017/mydatabase', {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

const db = mongoose.connection;

db.on('error', console.error.bind(console, 'MongoDB connection error:'));
db.once('open', () => {
  console.log('Connected to MongoDB');
});

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

Step 3: Define the API routes and their corresponding handlers.

app.get('/api/users', async (req: Request, res: Response) => {
  try {
    const users = await User.find();
    res.json(users);
  } catch (error) {
    console.error('Error fetching users:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
});

app.post('/api/users', async (req: Request, res: Response) => {
  try {
    const { name, email, age } = req.body;
    const newUser = new User({ name, email, age });
    const savedUser = await newUser.save();
    res.json(savedUser);
  } catch (error) {
    console.error('Error creating user:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
});

app.put('/api/users/:id', async (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    const { name, email, age } = req.body;
    const updatedUser = await User.findByIdAndUpdate(id, { name, email, age }, { new: true });
    res.json(updatedUser);
  } catch (error) {
    console.error('Error updating user:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
});

app.delete('/api/users/:id', async (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    await User.findByIdAndDelete(id);
    res.json({ message: 'User deleted successfully' });
  } catch (error) {
    console.error('Error deleting user:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
});

Step 4: Compile TypeScript to JavaScript and start the server.

npx ts-node index.ts

Conclusion:

Congratulations! You have successfully built a REST API using Node.js, Express.js, TypeScript, and MongoDB. You learned how to set up the project, define routes, connect to the database, and perform CRUD operations on a user collection. This stack provides a powerful foundation for creating scalable and maintainable web applications. Feel free to expand on this example and explore additional features and functionality to suit your specific project requirements. Happy coding!

0 0 votes
Article Rating
Subscribe
Notify of
guest
2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Shekhar
Shekhar
10 months ago

This article provides a concise and practical guide to creating a REST API using Node.js, Express.js, TypeScript, and MongoDB. A valuable resource for developers looking to build scalable and efficient web applications.