7-building-a-restful-api-with-nestjs-and-mongodb.html

Building a RESTful API with NestJS and MongoDB

In today's fast-paced digital landscape, building scalable and maintainable web applications is a top priority for developers. One of the most effective ways to achieve this is by creating a RESTful API. In this article, we will dive deep into the process of building a RESTful API using NestJS, a progressive Node.js framework, coupled with MongoDB, a popular NoSQL database. Whether you're a seasoned developer or just starting, this guide will provide you with actionable insights, code examples, and best practices to streamline your development process.

What is a RESTful API?

A RESTful API (Representational State Transfer) is an architectural style that allows different systems to communicate over the web using standard HTTP methods such as GET, POST, PUT, DELETE, etc. It is stateless, meaning that each request from a client contains all the information needed for the server to fulfill that request. RESTful APIs are widely used for building web services, and they enable seamless interaction between clients and servers.

Why Use NestJS and MongoDB?

NestJS is an excellent choice for building server-side applications due to its modular architecture, dependency injection, and support for TypeScript. It leverages the power of Express.js, making it easy to create robust APIs. MongoDB, on the other hand, is a flexible, schema-less database that allows for quick storage and retrieval of data.

Key Benefits of Using NestJS and MongoDB:

  • Type Safety: TypeScript enhances code quality and maintainability.
  • Modularity: NestJS promotes a modular structure, making it easier to organize and manage code.
  • Asynchronous Programming: Built-in support for async/await allows for handling asynchronous operations smoothly.
  • Scalability: Both NestJS and MongoDB are designed to scale as your application grows.

Setting Up the Development Environment

Before we dive into coding, let's set up our development environment.

Prerequisites

  • Node.js installed (v12 or later)
  • npm or yarn
  • MongoDB installed locally or access to a MongoDB Atlas account

Step 1: Create a New NestJS Project

To create a new NestJS project, open your terminal and run the following commands:

npm i -g @nestjs/cli
nest new rest-api-nestjs

Follow the prompts to set up your project. Once created, navigate to the project directory:

cd rest-api-nestjs

Step 2: Install Required Packages

To interact with MongoDB, you will need to install Mongoose. Run the following command:

npm install @nestjs/mongoose mongoose

Building the RESTful API

Now that we have our project set up, let’s create a simple RESTful API for managing a collection of items.

Step 3: Create a Mongoose Schema

Create a new file item.schema.ts in the src directory:

import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';

@Schema()
export class Item extends Document {
  @Prop({ required: true })
  name: string;

  @Prop()
  description: string;

  @Prop({ required: true })
  price: number;
}

export const ItemSchema = SchemaFactory.createForClass(Item);

Step 4: Create an Item Module

Next, we need to create a module to encapsulate our item-related functionality. Run the following command:

nest g module items

Now, create an items.service.ts file inside the items directory:

import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { Item } from './item.schema';

@Injectable()
export class ItemsService {
  constructor(@InjectModel(Item.name) private itemModel: Model<Item>) {}

  async create(itemData: Partial<Item>): Promise<Item> {
    const newItem = new this.itemModel(itemData);
    return newItem.save();
  }

  async findAll(): Promise<Item[]> {
    return this.itemModel.find().exec();
  }

  async findOne(id: string): Promise<Item> {
    return this.itemModel.findById(id).exec();
  }

  async update(id: string, itemData: Partial<Item>): Promise<Item> {
    return this.itemModel.findByIdAndUpdate(id, itemData, { new: true }).exec();
  }

  async delete(id: string): Promise<Item> {
    return this.itemModel.findByIdAndRemove(id).exec();
  }
}

Step 5: Create a Controller

Now it's time to create a controller to handle incoming requests. Create an items.controller.ts file in the items directory:

import { Body, Controller, Delete, Get, Param, Post, Put } from '@nestjs/common';
import { ItemsService } from './items.service';
import { Item } from './item.schema';

@Controller('items')
export class ItemsController {
  constructor(private readonly itemsService: ItemsService) {}

  @Post()
  create(@Body() itemData: Partial<Item>): Promise<Item> {
    return this.itemsService.create(itemData);
  }

  @Get()
  findAll(): Promise<Item[]> {
    return this.itemsService.findAll();
  }

  @Get(':id')
  findOne(@Param('id') id: string): Promise<Item> {
    return this.itemsService.findOne(id);
  }

  @Put(':id')
  update(@Param('id') id: string, @Body() itemData: Partial<Item>): Promise<Item> {
    return this.itemsService.update(id, itemData);
  }

  @Delete(':id')
  delete(@Param('id') id: string): Promise<Item> {
    return this.itemsService.delete(id);
  }
}

Step 6: Integrate Mongoose with NestJS

In the app.module.ts file, import the MongooseModule and your ItemsModule:

import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { ItemsModule } from './items/items.module';

@Module({
  imports: [
    MongooseModule.forRoot('mongodb://localhost/nest'), // Update with your MongoDB connection string
    ItemsModule,
  ],
})
export class AppModule {}

Testing the API

You can test your new API using Postman or Curl. Here are some example requests:

  • Create an Item: POST /items { "name": "Sample Item", "description": "This is a sample item.", "price": 29.99 }

  • Get All Items: GET /items

  • Get Item by ID: GET /items/{id}

  • Update Item: PUT /items/{id} { "price": 19.99 }

  • Delete Item: DELETE /items/{id}

Conclusion

Congratulations! You’ve just built a fully functional RESTful API using NestJS and MongoDB. This powerful combination allows you to create scalable and maintainable applications with ease. As you continue your development journey, consider exploring advanced features like authentication, validation, and error handling to enhance your API. By leveraging the strengths of NestJS and MongoDB, you're well-equipped to build robust web services that can withstand the demands of modern applications. Happy coding!

SR
Syed
Rizwan

About the Author

Syed Rizwan is a Machine Learning Engineer with 5 years of experience in AI, IoT, and Industrial Automation.