Introduction to NestJS
NestJS is built on top of Express (or Fastify) and combines elements from OOP, FP, and FRP programming styles. Its modular architecture helps developers structure their applications into modules, promoting separation of concerns and ensuring maintainability as your application grows.
Setting Up Your NestJS Project
Before diving into creating a REST API, let’s set up a new NestJS project.
-
Install the Nest CLI: You need to have the Nest CLI installed globally if you haven't done that already.
npm install -g @nestjs/cli
-
Create a new project: Use the CLI to scaffold a new NestJS project.
nest new my-nest-api
-
Run the application: Navigate into your new project directory and start your application.
cd my-nest-api npm run start
You should see your application running at
http://localhost:3000
.
Creating Your First RESTful Resource
NestJS encourages a resource-centric approach. Let’s create a simple resource called items
for our REST API.
-
Generate a new resource: Use the Nest CLI to create an
items
module.nest generate resource items
This command generates a new module with a controller and service file.
Understanding the Directory Structure
After generating the items
module, your project structure will look something like this:
src/
│
├── items/
│ ├── items.controller.ts
│ ├── items.module.ts
│ └── items.service.ts
│
├── app.module.ts
└── main.ts
items.controller.ts
: Handles incoming requests and returns responses for theitems
resource.items.service.ts
: Contains the business logic and data manipulation methods.items.module.ts
: A module that bundles the controller and service together.
Implementing Controller and Service Logic
Let’s implement basic CRUD operations in our items.controller.ts
and items.service.ts
.
Service Implementation (items.service.ts
)
import { Injectable } from '@nestjs/common'; @Injectable() export class ItemsService { private items = []; create(item: any) { this.items.push(item); return item; } findAll() { return this.items; } findOne(id: number) { return this.items[id]; } update(id: number, item: any) { this.items[id] = item; return item; } remove(id: number) { const item = this.items[id]; this.items.splice(id, 1); return item; } }
Controller Implementation (items.controller.ts
)
import { Controller, Get, Post, Body, Param, Put, Delete } from '@nestjs/common'; import { ItemsService } from './items.service'; @Controller('items') export class ItemsController { constructor(private readonly itemsService: ItemsService) {} @Post() create(@Body() item: any) { return this.itemsService.create(item); } @Get() findAll() { return this.itemsService.findAll(); } @Get(':id') findOne(@Param('id') id: number) { return this.itemsService.findOne(id); } @Put(':id') update(@Param('id') id: number, @Body() item: any) { return this.itemsService.update(id, item); } @Delete(':id') remove(@Param('id') id: number) { return this.itemsService.remove(id); } }
Testing Your REST API
You can test your REST API endpoints using Postman or any similar tool:
-
Create an item (POST):
- URL:
http://localhost:3000/items
- Body:
{ "name": "Item 1" }
- URL:
-
Get all items (GET):
- URL:
http://localhost:3000/items
- URL:
-
Get a single item (GET):
- URL:
http://localhost:3000/items/0
- URL:
-
Update an item (PUT):
- URL:
http://localhost:3000/items/0
- Body:
{ "name": "Updated Item 1" }
- URL:
-
Delete an item (DELETE):
- URL:
http://localhost:3000/items/0
- URL:
Conclusion
By following this tutorial, you've created a simple REST API using NestJS! You learned how to organize a NestJS application, structure controllers and services, and implement basic CRUD operations. With NestJS's modular architecture and TypeScript support, you're equipped to build more advanced and scalable server-side applications. Feel free to experiment with more complex features like middleware, guards, and interceptors as you continue your journey with NestJS.
Happy coding!