NestJS + PostgreSQL: Create Your First REST API

CRUD example with TypeORM

Building a REST API with NestJS, PostgreSQL, and TypeORM is a powerful, scalable choice for production apps. In this guide, youโ€™ll create a complete CRUD API (Create, Read, Update, Delete) using a simple Todo resource.

Weโ€™ll cover project setup, database configuration, an entity + DTOs, a service, a controller, and how to test with cURL.


Prerequisites

  • Node.js 18+
  • PostgreSQL 13+ running locally (with a database created)
  • npm or pnpm
  • Nest CLI:
npm i -g @nestjs/cli

1) Create the Project

nest new nest-pg-crud
# Choose npm or pnpm
cd nest-pg-crud

Install required packages:

npm i @nestjs/typeorm typeorm pg class-validator class-transformer dotenv

2) Environment Variables

Create a .env file in the project root:

# .env
PORT=3000
DB_HOST=localhost
DB_PORT=5432
DB_USER=postgres
DB_PASS=postgres
DB_NAME=nest_crud

Ensure the database nest_crud exists:

CREATE DATABASE nest_crud;

3) TypeORM + PostgreSQL Setup

Open src/app.module.ts and configure TypeORM (v0.3+ style):

// src/app.module.ts
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { TypeOrmModule } from '@nestjs/typeorm';
import { TodoModule } from './todo/todo.module';
import { Todo } from './todo/todo.entity';

@Module({
  imports: [
    ConfigModule.forRoot({ isGlobal: true }),
    TypeOrmModule.forRootAsync({
      useFactory: () => ({
        type: 'postgres',
        host: process.env.DB_HOST,
        port: Number(process.env.DB_PORT),
        username: process.env.DB_USER,
        password: process.env.DB_PASS,
        database: process.env.DB_NAME,
        entities: [Todo],
        synchronize: true, // turn off in production; use migrations instead
        logging: false,
      }),
    }),
    TodoModule,
  ],
})
export class AppModule {}

4) Create the Todo Module

Generate files:

nest g module todo
nest g service todo
nest g controller todo

5) Define the Entity

// src/todo/todo.entity.ts
import { Column, CreateDateColumn, Entity, PrimaryGeneratedColumn, UpdateDateColumn } from 'typeorm';

@Entity()
export class Todo {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Column({ length: 120 })
  title: string;

  @Column({ type: 'text', nullable: true })
  description?: string;

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

  @CreateDateColumn()
  createdAt: Date;

  @UpdateDateColumn()
  updatedAt: Date;
}

Register the entity in the module:

// src/todo/todo.module.ts
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Todo } from './todo.entity';
import { TodoService } from './todo.service';
import { TodoController } from './todo.controller';

@Module({
  imports: [TypeOrmModule.forFeature([Todo])],
  controllers: [TodoController],
  providers: [TodoService],
})
export class TodoModule {}

6) Create DTOs (Validation)

// src/todo/dto/create-todo.dto.ts
import { IsBoolean, IsOptional, IsString, MaxLength } from 'class-validator';

export class CreateTodoDto {
  @IsString()
  @MaxLength(120)
  title: string;

  @IsOptional()
  @IsString()
  description?: string;

  @IsOptional()
  @IsBoolean()
  completed?: boolean;
}
// src/todo/dto/update-todo.dto.ts
import { PartialType } from '@nestjs/mapped-types';
import { CreateTodoDto } from './create-todo.dto';

export class UpdateTodoDto extends PartialType(CreateTodoDto) {}

Enable global validation pipe in main.ts:

// src/main.ts
import { ValidationPipe } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.useGlobalPipes(new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true, transform: true }));
  await app.listen(process.env.PORT || 3000);
}
bootstrap();

Install @nestjs/mapped-types (for PartialType) if not present:

npm i @nestjs/mapped-types

7) Service (Business Logic)

// src/todo/todo.service.ts
import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, FindOptionsWhere, ILike } from 'typeorm';
import { Todo } from './todo.entity';
import { CreateTodoDto } from './dto/create-todo.dto';
import { UpdateTodoDto } from './dto/update-todo.dto';

@Injectable()
export class TodoService {
  constructor(
    @InjectRepository(Todo)
    private readonly repo: Repository<Todo>,
  ) {}

  async create(dto: CreateTodoDto): Promise<Todo> {
    const todo = this.repo.create(dto);
    return this.repo.save(todo);
  }

  async findAll(q?: string, page = 1, limit = 10): Promise<{ data: Todo[]; total: number; page: number; limit: number }> {
    const where: FindOptionsWhere<Todo>[] = q
      ? [{ title: ILike(`%${q}%`) }, { description: ILike(`%${q}%`) }]
      : [{}];

    const [data, total] = await this.repo.findAndCount({
      where,
      order: { createdAt: 'DESC' },
      skip: (page - 1) * limit,
      take: limit,
    });

    return { data, total, page, limit };
  }

  async findOne(id: string): Promise<Todo> {
    const todo = await this.repo.findOne({ where: { id } });
    if (!todo) throw new NotFoundException('Todo not found');
    return todo;
  }

  async update(id: string, dto: UpdateTodoDto): Promise<Todo> {
    const todo = await this.findOne(id);
    Object.assign(todo, dto);
    return this.repo.save(todo);
  }

  async remove(id: string): Promise<void> {
    const todo = await this.findOne(id);
    await this.repo.remove(todo);
  }
}

8) Controller (Routes)

// src/todo/todo.controller.ts
import { Body, Controller, Delete, Get, Param, Patch, Post, Query } from '@nestjs/common';
import { TodoService } from './todo.service';
import { CreateTodoDto } from './dto/create-todo.dto';
import { UpdateTodoDto } from './dto/update-todo.dto';

@Controller('todos')
export class TodoController {
  constructor(private readonly service: TodoService) {}

  @Post()
  create(@Body() dto: CreateTodoDto) {
    return this.service.create(dto);
  }

  @Get()
  findAll(
    @Query('q') q?: string,
    @Query('page') page = '1',
    @Query('limit') limit = '10',
  ) {
    return this.service.findAll(q, Number(page), Number(limit));
  }

  @Get(':id')
  findOne(@Param('id') id: string) {
    return this.service.findOne(id);
  }

  @Patch(':id')
  update(@Param('id') id: string, @Body() dto: UpdateTodoDto) {
    return this.service.update(id, dto);
  }

  @Delete(':id')
  remove(@Param('id') id: string) {
    return this.service.remove(id);
  }
}

9) Start the Server

npm run start:dev
# API runs at http://localhost:3000

10) Test the Endpoints (cURL)

Create

curl -X POST http://localhost:3000/todos \
  -H "Content-Type: application/json" \
  -d '{"title":"Learn NestJS","description":"Build a CRUD API","completed":false}'

List (with pagination + search)

curl "http://localhost:3000/todos?page=1&limit=5&q=nest"

Get by ID

curl http://localhost:3000/todos/<UUID>

Update

curl -X PATCH http://localhost:3000/todos/<UUID> \
  -H "Content-Type: application/json" \
  -d '{"completed": true}'

Delete

curl -X DELETE http://localhost:3000/todos/<UUID>

Production Tips

  • Turn off synchronize and use migrations for schema changes.
  • Add a global exception filter and logging middleware.
  • Secure env vars with a proper config and secrets management.
  • Dockerize Postgres + API for consistent environments.

Wrap-Up

You now have a fully working NestJS + PostgreSQL REST API with TypeORM, DTO validation, pagination, and search. This structure scales well for real projectsโ€”just add modules for new domains and keep business logic inside services.


Optional: Package Scripts

// package.json (partial)
{
  "scripts": {
    "start": "nest start",
    "start:dev": "nest start --watch",
    "build": "nest build",
    "format": "prettier --write \"src/**/*.ts\"",
    "lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix"
  }
}

Comments

102 responses to “NestJS + PostgreSQL: Create Your First REST API”

  1. Honestly, the depth of this analysis is helpful. Trying to grasp all the mechanisms described, especially for beginners, is a lot. I might need to check out 7jl login app download apk later to see how simple the actual process is. ๐Ÿค”

  2. This is a solid foundation for scalable backend architecture. Moving beyond basic CRUD, consider how transaction management and eventual consistency impact real-world user flows. Building robust, high-availability systems-whether for a corporate service or a high-traffic platform like jil29 link-requires this level of structural rigor. Excellent guide!

  3. Perfect for those who want a straightforward gaming experience without too much fuss. Very intuitive layout over at win29au

  4. Such a fun way to unwind after work. The games are exciting and the registration was super quick. I really enjoy juegolota

  5. I’ve been looking for a reliable app like this for a while. The interface is super smooth and the payouts are actually fast. Highly recommended for anyone in the region! Check out 4999bdtapp

  6. Thatโ€™s a fascinating take on longshot strategies! Itโ€™s smart to consider value beyond just the favorites. Thinking about quick access & security, like with 36jl casinoโ€™s fast registration, really helps focus on the bets themselves! ๐Ÿ‘

  7. Finally found a platform that truly connects! The KingphaPK app download apk is smooth and the community vibe is amazing. Check out kingphapk vip to join the fun today!

  8. I switched from my usual spot and honestly I do not plan on going back. The chat support is always friendly and the withdrawal process is surprisingly fast. It just feels like a community that genuinely enjoys gaming. 19jl

  9. I spent weeks testing different platforms before finding one that actually delivers on fair gameplay. The slot selection is massive and the payout schedule never disappoints. I appreciate how transparent everything is from bonus terms to withdrawal limits. It is refreshing to find a team that truly cares about their players. iddanatotoslot

  10. Logging in here feels like stepping into a VIP lounge where everything just works. I appreciate how quickly they verify new accounts and how transparent the bonus terms really are. No hidden traps just honest gameplay and fair chances to win big. The support crew responds in record time whenever I need a hand. Visit roolicasinologin and experience the difference yourself

  11. Finally a site that truly gets the Latin American gaming scene and brings a VIP treatment to everyone who signs up. The games load perfectly on mobile and I never have to worry about hidden conditions. It is rare to find this level of respect for everyday players. vipganer

  12. This trading platform has completely changed how I approach the forex market. The charts are clean execution is lightning fast and the educational resources helped me improve my strategy significantly. A solid choice for both new and experienced traders. 888fx

  13. This casino quietly built a solid reputation among locals and I can totally see why. The welcome package is fair, game providers are top tier and withdrawals never get stuck in review for days. A trustworthy friend for anyone chasing lucky streaks. Come join 578jilicasino

  14. The onboarding process seems straightforward, but experienced players know the real edge is in understanding the mechanics, not just the sign-up. Check out P7777 vip for deeper insights.

  15. The focus on mobile convenience is noted, but remember that true platform value lies in verifiable transaction integrity. For deeper analysis, check out 234win 444 download apk. Statistical rigor always precedes entertainment.

  16. Everything from the layout to the game selection is top-notch. I feel very secure playing here and the rewards are generous. Go check pknb999 right now.

  17. Really impressed with the variety of betting options available. It is easy to navigate even for beginners. I’m sticking with 2nnbet for my weekend games.

  18. This interface feels clean, which is rare. While the focus on simple fun is noted, checking out big bunny com‘s overall usability against competitors would be smart for any serious player.

  19. This platform truly stands out with its smooth interface and top notch game selection. The support team is super helpful and I trust them for every session at alpha66online

  20. Even my relaxation time has a fun twist with this platform. The games are so smoothly integrated that playing feels as comfortable as settling into my favorite couch. A truly cozy escape for any downtime. masterbed

  21. Being a player in the Philippines I know how hard it is to find a site that actually pays out on time. This one changed my routine completely. I love the live dealer tables and the payment options work perfectly with local banks. The interface is clean and I never feel lost while placing my bets. Highly recommend it to everyone looking for a trustworthy platform. nn7777ph

  22. The energy on this site is awesome. The games are exciting and the promotions are always updated. Go to phfierylogin

  23. The login process is super quick and the games are top notch. Had a great run last night and won big. Highly recommend 178jililogin

  24. This setup looks solid, especially the variety. For deeper strategy, check out cb6 app เฆ•เงเฆฏเฆพเฆธเฆฟเฆจเง‹. Understanding the mechanics is key; don’t just focus on the interface, analyze the payout structures!

  25. I love the way the promotions are handled here. Everything is transparent and the winning streaks are real. You should definitely try laga88slotlogin today.

  26. As someone who loves betting on sports and casino games, this platform delivers exactly what players need. Fast payouts, fair odds, and a design that does not waste a single click. I trust it more than any other site I have tried recently. br017bet

  27. Solid analysis! Strategic gameplay is key, and platforms like philwin link login seem to understand that, offering diverse options. Quick deposits (under 45s!) are a huge plus for serious players too. ๐Ÿ‘

  28. Such an exciting atmosphere! The games are high quality and the rewards are actually achievable. If you like gaming, pkk999casino is a must-visit.

  29. Best experience so far! The interface is smooth and I didn’t encounter any lags during my session. Highly recommend kr5bet to everyone.

  30. The graphics are stunning and the gameplay is very fluid. It is definitely one of the most exciting sites I have used recently. Give mxhotya a try.

  31. The mobile app is a game changer. I can play anywhere without any lag or crashing. Highly recommend downloading bcgameapp for a better experience.

  32. The login process is so fast and I never have issues accessing my account. Really impressed with the service at 6jililogin.

  33. Everything about this place feels welcoming. The promos are genuine and not just bait. I’m really enjoying my time at idpitaslot.

  34. Finally found a site that actually works smoothly here in Brazil. The interface is super intuitive and the payouts are fast. Definitely my new favorite spot! brasil777br

  35. Really liking the variety of options here. It is easy to navigate and the customer support team is actually helpful and responsive. Five stars! 688jilicomlogin

  36. Love the variety of games here. I had a great run last night and the customer support was very helpful with my deposit. Check out phjilibit

  37. Really liking the rewards system on this app. It keeps things exciting and the prizes are actually attainable. bdbb444app is my new favorite.

  38. The graphics on these slots are top notch. It feels much more immersive than other sites I’ve tried. ph20jili is definitely my new favorite spot.

  39. Just hit a decent win here and the withdrawal was processed way faster than I expected. It is hard to find honest sites these days but inyouo777 delivers.

  40. This place completely changed how I spend my free time. The community is so welcoming and the game selection keeps me entertained for hours. Every spin brings a little thrill. bdclub999

  41. The slots here are actually paying out. I hit a decent jackpot today and the withdrawal was processed instantly. Cheers to unsur138slot.

  42. The app is very lightweight and doesn’t lag at all on my phone. Downloading bdbc777apk was the best decision for gaming on the go.

  43. The promotions here are top notch and they actually reward loyal players. I am having a blast with the current events on brasino777br.

  44. The graphics are stunning and the gameplay is very fair. I had a huge win last night and the withdrawal was instant. Visit 777richjililogin now.

  45. Finally found a place that actually pays out on time. The interface is super intuitive and easy to navigate. Check out jitu100login if you want a reliable spot to play.

  46. The bonuses here are actually legit and easy to claim. I had a great run yesterday and the support team was very helpful. 87a777plataforma is definitely my new favorite.

  47. Best JILI experience I have had so far. The graphics are crisp and the gameplay is fair. Highly recommend ph288jili to everyone in the PH

  48. The app interface is super smooth and the login process is a breeze. I really love how fast the games load. Definitely a great choice for anyone looking for a reliable platform. Check out 666jililoginapp

  49. Best experience I’ve had in a long time. The community is friendly and the wins are consistent. I’m sticking with idkastil89 from now on.

  50. Logging in is a breeze and I never face any glitches. It is the most stable app I have used so far. Just head over to bjbajiapplogin.

  51. Love the selection of live dealer games. It really feels like I am at a real casino without leaving my living room. Cheers to rk88bet for the great setup.

  52. Honestly the best experience I’ve had in a while. The games are super addictive and everything loads instantly. Love the vibe here at ph711jili

  53. If you are looking for a place with a good vibe and fair odds, this is it. I’ve had some pretty decent wins here recently. Check out pk777daulat for yourself.

  54. The site’s structure is fine, but always remember to cross-reference platform rules. Don’t just trust the shiny banners; check the fine print on dbajee mobile. Safety first, always!

  55. Setting up my account took less than two minutes. The navigation is intuitive and I didn’t get lost at all. idsersanbet is top notch.

  56. It’s great seeing platforms like this prioritize safety! Remember that support is key; self-care always comes first when exploring any site. Check out 33win85 app casino for a balanced view. โœจ

  57. The game selection is huge and the graphics are crisp. It feels like a premium experience from start to finish. Love spending my free time on phlodibet999.

  58. I love how intuitive the layout is. Even for beginners, it is very easy to navigate. Definitely spending more time on vnok83866 from now on.

  59. Great experience so far! The games are fair and the payouts are fast. I am really enjoying my time on idjaya77 lately.

  60. I’ve tried a few sites lately but this one really stands out. The payouts are fast and the interface is super smooth. Highly recommend br600betlucky for anyone looking for a legit spot.

  61. The live dealer tables on ph345casino transport me straight to the floor without leaving my couch. Dealers are friendly and the chat flows naturally. I love how transparent the bonus structure is and how quickly payouts arrive at my door. ph345casino

  62. The community here is awesome and the games are always updated. If you want a reliable platform, go with cr777game.

  63. I was struggling to get back into my account but this alternative link saved the day. Super easy to navigate. Check out zuma78linkalternatif if you are having access issues.

  64. I love how simple it is to get back into my account every time. No complicated steps, just straightforward gaming. dbt88login makes things so much easier.

  65. A hidden gem for sure. The odds are better than most of the big name sites I’ve used. Glad I found bd0kzz.

  66. I’ve been using this platform for a while now and the payouts are surprisingly fast. Definitely one of the most reliable apps I have tried lately. Check it out at 80winbetapp

  67. This site has a great vibe and the winning odds feel fair. I had a great run last night and the withdrawal was fast. Give brricowin a try

  68. I felt like I had some real luck today! The platform is very user-friendly even for beginners. I will definitely be returning to pklucky93game very soon.

  69. Really enjoying the bonuses here. I managed to hit a nice streak last night and the withdrawal was processed almost instantly. Very reliable site. See more at br77888bet

  70. I have tried many sites but this one stands out for its reliability. Fast withdrawals and great odds. Trust kr789win

  71. Honestly the best experience I have had with a slot site recently. The payouts are fair and the interface is super smooth. Definitely check out jili988casinologin if you want a reliable place to play.

  72. Logging in is fast and the system is very stable. No more annoying crashes during the most exciting moments of the game! 203publogin

  73. I am really enjoying the bonuses they offer for new users. It is a great way to start. The app is very stable too. Check out 168jlloginapp

  74. I’m really impressed with the win rates here. It feels much more balanced than other sites I’ve tried. 288wingame is definitely worth your time.

  75. Absolute game changer for me. The variety of rooms and the community vibe are just amazing. I spend most of my free time on vnhitclubpro now.

  76. Everything about this place feels high quality. From the graphics to the payment options, it is all spot on. Try your luck at br1cassino.

  77. Interesting read! Responsible gaming is key, and platforms like betmgm casino game seem to prioritize security โ€“ good to see those verification steps detailed. Always bet within your means, folks! ๐Ÿ‘

  78. Solid experience so far. The community is helpful and the site layout is very intuitive. If you are looking for quality and reliability then brkk123 is the way to go.

  79. The variety of games available is impressive. I really appreciate how stable the platform is even during peak hours. Check out vnh13game if you want a reliable place to play.

  80. Really happy with the variety of games available here. There is always something new to try and the rewards are actually fair. Cheers to phph945

  81. I have been searching for a trustworthy sports betting platform for quite a while and finally settled on this one. The in play odds update instantly and the cashout button works smoothly whenever I want to lock in profits. Customer support actually answers fast and explains the rules in plain language. I appreciate how straightforward everything feels from sign up to withdrawal. appsportbet

  82. The PAGCOR licensing angle is key for platform integrity. Analyzing the deposit methods suggests robust integration. For more deep dives on tech stacks, check out arioncasino app casino. Solid framework!

  83. The app version is just seamless. I can play on the go without any lag, which is a huge plus for me. Highly recommend bd7c7777apps to everyone.

  84. Registering was a breeze and I started playing in less than two minutes. The bonuses for new players are actually worth it. aurahokidaftar is legit

  85. The mobile version works perfectly and I can play anywhere on the go. Very convenient and fast loading times. Try 17jilicasinologin for a smooth ride.

  86. The variety of slots here is insane. I spent the whole night playing and had a great time. Definitely visit okjilicasino if you love slots.

  87. Super fast deposits and withdrawals which is all I really care about. Great service and great games at jili168phcom.

  88. The VIP treatment here is actually legit. I feel like a valued player and the rewards keep coming. You should try vnynvn88vip for a more premium gaming feel.

  89. The welcome bonus was a great way to start. I managed to double my initial deposit in one evening. krbet3 is honestly a hidden gem.

  90. The variety of games here is insane. I spent hours exploring different slots and they are all high quality. pkp998 is where the real action is.

  91. This site has a great selection of Jili games that actually pay out. I’ve spent a few hours here and the experience has been purely awesome. Check out phjili65.

  92. Super easy to get into my account. The page loads fast even on my mobile data which is a huge plus for me. jilioklogin

  93. The variety of games here is impressive. I spent a few hours exploring and everything just works perfectly. Great vibes over at bdjoya9best.

  94. If you are looking for a real solution to win more often, this is the place. The tips and the platform are top notch. idsolusiwin is a hidden gem.

  95. Perfect for those who want a reliable and fast service. The layout is clean and the payment methods are very flexible. Love it! krbeetwiner

  96. Solid platform with a very professional feel. I feel safe depositing my funds here. Cheers to armorbet78.

  97. Great article! Seeing more platforms prioritize a smooth mobile experience is key. Quick registration & easy deposits (like with jilli slot download) really make a difference for players in the Philippines! ๐Ÿ‘

  98. Honestly the best experience I have had with a slot site recently. The payouts are fair and the interface is super smooth. Definitely check out jili988casinologin if you want a reliable place to play.

  99. Finally found a platform that doesn’t lag during peak hours. The registration process was a breeze and I started playing in minutes. Give bdck4444bet a try.

  100. Best place to unwind after work. The games are fair and the withdrawal process is straightforward and easy. Try phjili969

  101. The app is super lightweight and doesn’t crash. Perfect for playing on the go during my commute. Download bdtk444app now.

  102. Finally an app that does not crash every five minutes. The login process is seamless and the graphics are top notch. Love how convenient it is to play on the go via evojililoginapp.

Leave a Reply

Your email address will not be published. Required fields are marked *