logologo
  • AI Tools

    DB Query GeneratorMock InterviewResume BuilderLearning Path GeneratorCheatsheet GeneratorAgentic Prompt GeneratorCompany ResearchCover Letter Generator
  • XpertoAI
  • AI Interviewer
  • MVP Ready
  • Resources

    CertificationsTopicsExpertsCollectionsArticlesQuestionsVideosJobs
logologo

Elevate Your Coding with our comprehensive articles and niche collections.

Useful Links

  • Contact Us
  • Privacy Policy
  • Terms & Conditions
  • Refund & Cancellation
  • About Us

Resources

  • Xperto-AI
  • Certifications
  • Python
  • GenAI
  • Machine Learning

Interviews

  • DSA
  • System Design
  • Design Patterns
  • Frontend System Design
  • ReactJS

Procodebase © 2024. All rights reserved.

Level Up Your Skills with Xperto-AI

A multi-AI agent platform that helps you level up your development skills and ace your interview preparation to secure your dream job.

Launch Xperto-AI

Building REST APIs with NestJS

author
Generated by
ProCodebase AI

10/12/2024

NestJS

Sign in to read full article

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.

  1. 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
  2. Create a new project: Use the CLI to scaffold a new NestJS project.

    nest new my-nest-api
  3. 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.

  1. 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 the items 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" }
  • Get all items (GET):

    • URL: http://localhost:3000/items
  • Get a single item (GET):

    • URL: http://localhost:3000/items/0
  • Update an item (PUT):

    • URL: http://localhost:3000/items/0
    • Body: { "name": "Updated Item 1" }
  • Delete an item (DELETE):

    • URL: http://localhost:3000/items/0

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!

Popular Tags

NestJSREST APIsTypeScript

Share now!

Like & Bookmark!

Related Collections

  • NestJS Mastery: Modern Backend Development

    10/12/2024 | NestJS

Related Articles

  • Understanding Modules in NestJS

    10/12/2024 | NestJS

  • WebSocket Integration in NestJS

    10/12/2024 | NestJS

  • Setting Up a NestJS Project

    10/12/2024 | NestJS

  • Working with MongoDB using Mongoose in NestJS

    10/12/2024 | NestJS

  • Building GraphQL APIs with NestJS

    10/12/2024 | NestJS

  • Introduction to NestJS Framework

    10/12/2024 | NestJS

  • Microservices with NestJS

    10/12/2024 | NestJS

Popular Category

  • Python
  • Generative AI
  • Machine Learning
  • ReactJS
  • System Design