8-building-restful-apis-with-nestjs-and-typescript.html

Building RESTful APIs with NestJS and TypeScript

In the world of web development, creating efficient and scalable APIs is essential. RESTful APIs, in particular, have gained immense popularity due to their simplicity and effectiveness. With the rise of TypeScript as a preferred language for building applications, NestJS has emerged as a powerful framework for developing robust RESTful APIs. In this article, we will explore how to build RESTful APIs using NestJS and TypeScript, covering definitions, use cases, and actionable insights.

What is NestJS?

NestJS is a progressive Node.js framework built with TypeScript that is designed to create scalable and maintainable server-side applications. It leverages the power of TypeScript, making it type-safe and allowing developers to build applications that are easier to understand and maintain. NestJS is heavily inspired by Angular, which means it encourages modular development, dependency injection, and the use of decorators.

Why Use NestJS for RESTful APIs?

  • Modular Architecture: NestJS promotes a modular architecture, making it easier to manage code and dependencies.
  • Type Safety: TypeScript provides type safety, reducing runtime errors and improving code quality.
  • Built-in Support for Middleware: Easily integrate middleware to handle requests and responses.
  • Ecosystem and Community: Strong community support and a rich ecosystem of libraries and tools.

Setting Up Your NestJS Project

To get started with NestJS, you first need to set up your development environment. Here’s how to do it step-by-step:

Step 1: Install Node.js and Nest CLI

Ensure you have Node.js installed on your machine. You can download it from nodejs.org. After installing Node.js, install the Nest CLI globally using npm:

npm install -g @nestjs/cli

Step 2: Create a New Project

Create a new NestJS project by running:

nest new my-nest-api

This command will scaffold a new NestJS application in a folder named my-nest-api.

Step 3: Navigate to Your Project Directory

Change into your project directory:

cd my-nest-api

Step 4: Install Required Dependencies

For building RESTful APIs, you will need some additional dependencies. Install them using:

npm install @nestjs/typeorm typeorm sqlite3

This command installs TypeORM for database interactions and SQLite as an example database.

Creating a Simple RESTful API

Let’s build a simple RESTful API to manage a collection of tasks. We’ll go through defining a task entity, creating a service, and building a controller.

Step 5: Create a Task Entity

Create a new file called task.entity.ts in the src directory:

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

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

  @Column()
  title: string;

  @Column({ default: false })
  completed: boolean;
}

Step 6: Create a Task Service

Now, create a service that will handle the business logic for tasks. Create a file called task.service.ts:

import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Task } from './task.entity';

@Injectable()
export class TaskService {
  constructor(
    @InjectRepository(Task)
    private taskRepository: Repository<Task>,
  ) {}

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

  create(task: Task): Promise<Task> {
    return this.taskRepository.save(task);
  }

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

Step 7: Create a Task Controller

Next, you’ll create a controller that will manage incoming requests. Create a file called task.controller.ts:

import { Controller, Get, Post, Body, Delete, Param } from '@nestjs/common';
import { TaskService } from './task.service';
import { Task } from './task.entity';

@Controller('tasks')
export class TaskController {
  constructor(private readonly taskService: TaskService) {}

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

  @Post()
  create(@Body() task: Task): Promise<Task> {
    return this.taskService.create(task);
  }

  @Delete(':id')
  remove(@Param('id') id: string): Promise<void> {
    return this.taskService.remove(+id);
  }
}

Step 8: Register the Module

Finally, register the entity, service, and controller in a module. Create a file called task.module.ts:

import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Task } from './task.entity';
import { TaskService } from './task.service';
import { TaskController } from './task.controller';

@Module({
  imports: [TypeOrmModule.forFeature([Task])],
  providers: [TaskService],
  controllers: [TaskController],
})
export class TaskModule {}

Step 9: Connect to the Database

Update your app.module.ts to include TypeORM and your TaskModule:

import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { TaskModule } from './task/task.module';

@Module({
  imports: [
    TypeOrmModule.forRoot({
      type: 'sqlite',
      database: 'db.sqlite',
      entities: [__dirname + '/**/*.entity{.ts,.js}'],
      synchronize: true,
    }),
    TaskModule,
  ],
})
export class AppModule {}

Step 10: Run Your Application

Finally, run your application with:

npm run start

You can now test your API using tools like Postman or curl. Your endpoints include:

  • GET /tasks: Retrieve all tasks.
  • POST /tasks: Create a new task (send a JSON body).
  • DELETE /tasks/:id: Remove a task by ID.

Conclusion

Building RESTful APIs with NestJS and TypeScript is an efficient way to create scalable server-side applications. With its modular architecture and type safety, NestJS empowers developers to write clean and maintainable code. By following the steps outlined in this article, you can quickly create a simple API and expand upon it based on your application's needs.

Next Steps

  • Explore advanced features like authentication, validation, and error handling.
  • Implement pagination for your API.
  • Consider using additional TypeORM features like relations for more complex applications.

With NestJS and TypeScript, the possibilities are endless, and you’re well on your way to becoming a proficient API developer!

SR
Syed
Rizwan

About the Author

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