Route Parameters

Capture dynamic segments of the URL with @Param and query values with @Query.

Syntax@Get(':id') findOne(@Param('id') id: string)

Routes often contain dynamic parts, like an id. Declare them in the path with a colon and read them with the @Param() decorator.

Params vs query

  • Route params - part of the path, e.g. /users/42. Read with @Param('id').
  • Query params - after the ?, e.g. /users?role=admin. Read with @Query('role').

Values arrive as strings; convert or validate them with pipes when you need numbers.

Example

Example Β· typescript
import { Controller, Get, Param, Query } from '@nestjs/common';

@Controller('users')
export class UsersController {
  @Get(':id')                     // GET /users/42
  findOne(@Param('id') id: string) {
    return `user ${id}`;
  }

  @Get()                          // GET /users?role=admin
  findByRole(@Query('role') role: string) {
    return `role ${role}`;
  }
}

When to use it

  • A developer uses @Param("id") to extract the product ID from GET /products/42 and fetch the matching record from the database.
  • An API uses @Query("page") and @Query("limit") to implement paginated list endpoints without putting pagination data in the URL path.
  • A developer uses @Param() (no argument) to receive the full params object when a route has multiple dynamic segments like /orgs/:orgId/repos/:repoId.

More examples

Single route parameter

Shows how @Param("id") extracts the dynamic :id segment from the URL path.

Example Β· ts
import { Controller, Get, Param } from '@nestjs/common';

@Controller('products')
export class ProductsController {
  @Get(':id')
  findOne(@Param('id') id: string) {
    return { id };   // e.g. GET /products/42 β†’ { id: '42' }
  }
}

Query parameters for pagination

Demonstrates reading optional query parameters with defaults for a paginated list endpoint.

Example Β· ts
import { Controller, Get, Query } from '@nestjs/common';

@Controller('posts')
export class PostsController {
  @Get()
  findAll(
    @Query('page') page = '1',
    @Query('limit') limit = '10',
  ) {
    return { page: +page, limit: +limit };
  }
}

Multiple path params object

Uses @Param() without a key to receive the full params object when there are multiple dynamic segments.

Example Β· ts
import { Controller, Get, Param } from '@nestjs/common';

@Controller('orgs/:orgId/repos')
export class ReposController {
  @Get(':repoId')
  findOne(@Param() params: Record<string, string>) {
    const { orgId, repoId } = params;
    return { orgId, repoId };
  }
}

Discussion

  • Be the first to comment on this lesson.