Creating a Simple E-Commerce API with NestJS

@rnab
3 min readJan 17, 2025

--

The advent of e-commerce has revolutionized the way we shop and do business. With this increasing demand, having a robust, scalable, and efficient e-commerce API is crucial. In this article, we’ll explore how to create a simple e-commerce API using NestJS, a progressive Node.js framework for building efficient and scalable server-side applications.

Why NestJS?

NestJS is built with TypeScript, a superset of JavaScript that adds static types. It leverages the power of tools such as Express.js (or optionally Fastify), giving you a solid platform to build upon.

Some of the key benefits of NestJS include:

  1. Modularity: Encourages a modular architecture and helps in organizing code effectively.
  2. Dependency Injection: Provides built-in dependency injection, promoting lean and maintainable code.
  3. TypeScript: Embraces TypeScript fully, offering type safety and tooling benefits.

Setting Up the Project

First, ensure that you have Node.js and npm installed. You can verify this by running:

node -v
npm -v

If these are not installed, refer to the official Node.js website for installation instructions.

To begin, let’s create a new NestJS project using the Nest CLI:

npm i -g @nestjs/cli
nest new e-commerce-api

Navigate into the project directory:

cd e-commerce-api

Installing Dependencies

NestJS provides a rich ecosystem with built-in modules and packages. For this project, we will need additional packages for data validation and interaction with a database. We’ll use TypeORM for ORM support along with SQLite as our database:

npm install @nestjs/typeorm typeorm sqlite3 class-validator class-transformer

Designing the E-Commerce API

We’ll design a basic API that includes the following features:

  1. Products CRUD Operations: Create, Read, Update, Delete products.

Creating the Product Module

Start by generating a product module, service, and controller:

nest g module product
nest g service product
nest g controller product

Setting Up the Database

Configure the database connection in src/app.module.ts:

import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Product } from './product/product.entity';
import { ProductModule } from './product/product.module';

@Module({
imports: [
TypeOrmModule.forRoot({
type: 'sqlite',
database: 'ecommerce.db',
entities: [Product],
synchronize: true,
}),
ProductModule,
],
})
export class AppModule {}

Defining the Product Entity

In src/product/product.entity.ts, we define our product entity:

import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';

@Entity()
export class Product {
@PrimaryGeneratedColumn()
id: number;

@Column()
name: string;

@Column()
description: string;

@Column()
price: number;
}

Creating the Product DTO

It’s essential to define Data Transfer Objects (DTOs) to validate and type-check the data:

Create src/product/dto/create-product.dto.ts:

import { IsString, IsInt, IsPositive } from 'class-validator';

export class CreateProductDto {
@IsString()
name: string;

@IsString()
description: string;

@IsInt()
@IsPositive()
price: number;
}

Implementing the Product Service

In src/product/product.service.ts, implement the service to handle product logic:

import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Product } from './product.entity';
import { CreateProductDto } from './dto/create-product.dto';

@Injectable()
export class ProductService {
constructor(
@InjectRepository(Product)
private readonly productRepository: Repository<Product>,
) {}

async create(createProductDto: CreateProductDto): Promise<Product> {
const product = this.productRepository.create(createProductDto);
return this.productRepository.save(product);
}

findAll(): Promise<Product[]> {
return this.productRepository.find();
}

findOne(id: number): Promise<Product> {
return this.productRepository.findOne(id);
}

async update(id: number, updateProductDto: CreateProductDto): Promise<Product> {
await this.productRepository.update(id, updateProductDto);
return this.productRepository.findOne(id);
}

async remove(id: number): Promise<void> {
await this.productRepository.delete(id);
}
}

Building the Product Controller

Define the routes in src/product/product.controller.ts:

import { Controller, Get, Post, Body, Param, Delete, Put } from '@nestjs/common';
import { ProductService } from './product.service';
import { CreateProductDto } from './dto/create-product.dto';
import { Product } from './product.entity';

@Controller('products')
export class ProductController {
constructor(private readonly productService: ProductService) {}

@Post()
create(@Body() createProductDto: CreateProductDto): Promise<Product> {
return this.productService.create(createProductDto);
}

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

@Get(':id')
findOne(@Param('id') id: number): Promise<Product> {
return this.productService.findOne(id);
}

@Put(':id')
update(
@Param('id') id: number,
@Body() updateProductDto: CreateProductDto,
): Promise<Product> {
return this.productService.update(id, updateProductDto);
}

@Delete(':id')
remove(@Param('id') id: number): Promise<void> {
return this.productService.remove(id);
}
}

Running the Application

With everything set up, you can run the application using:

npm run start

Your API should now be accessible at http://localhost:3000/products.

Conclusion

In this article, we have created a simple yet functional e-commerce API using NestJS. This setup provides a solid foundation on which you can build more advanced features such as user authentication, order processing, payments integration, etc. NestJS’s modular architecture makes it easy to scale and maintain your application as your business grows.

Feel free to fork the repository and start building out your new e-commerce platform! If you have any questions, feel free to leave a comment below or reach out to me on Twitter.

Happy coding!

--

--

@rnab
@rnab

Written by @rnab

Typescript, Devops, Kubernetes, AWS, AI/ML, Algo Trading

No responses yet