ArticleZip > How To Create Nested Routes With Parameters Using Nestjs

How To Create Nested Routes With Parameters Using Nestjs

NestJS is a popular framework for building efficient and scalable server-side applications with Node.js. One powerful feature it offers is the ability to create nested routes with parameters. This allows you to organize your endpoints in a logical way and handle dynamic data effectively. In this guide, we will walk you through the process of creating nested routes with parameters in NestJS.

To create nested routes in NestJS, you need to utilize the routing capabilities provided by the framework. NestJS uses decorators to define routes, controllers, and parameters, making it easy to build RESTful APIs.

First, let's start by setting up a basic NestJS application. If you haven't already installed NestJS, you can do so by running the following command:

Bash

npm install -g @nestjs/cli
nest new project-name

Once you have your NestJS project set up, let's create a new controller. Controllers are responsible for handling incoming requests and returning responses. Create a new controller file, for example, `cats.controller.ts`, and define a class with the `@Controller` decorator:

Typescript

import { Controller, Get } from '@nestjs/common';

@Controller('cats')
export class CatsController {
  @Get()
  findAll(): string {
    return 'This action returns all cats';
  }
}

In the example above, we created a `CatsController` with a route `/cats` that responds to `GET` requests by returning a simple message.

Next, let's create a nested route within the `CatsController`. To do this, we can define another method within the controller class and use the `@Get` decorator with a specific route parameter:

Typescript

@Get(':id')
findOne(@Param('id') id: string): string {
  return `This action returns a cat with the ID ${id}`;
}

In this code snippet, we added a new `findOne` method that takes a route parameter `id`. When a request is made to `/cats/1`, for example, this method will return a message with the specific ID of the cat.

To test your nested routes with parameters, you can run your NestJS application and make requests using tools like Postman or curl. Start your NestJS application by running:

Bash

npm run start

Open your browser or API testing tool and send a `GET` request to `http://localhost:3000/cats/1`. You should see the response message indicating that a cat with the ID of 1 is being returned.

Congratulations! You have successfully created nested routes with parameters in NestJS. This powerful feature allows you to structure your API endpoints in a clear and organized manner, making it easier to manage dynamic data in your applications.

Keep exploring the capabilities of NestJS and experiment with different route configurations to build robust and efficient server-side applications. Happy coding!