NestJS How to get Request path and query parameters with code examples

This tutorial shows you how to use query parameters in the NestJS Application. It includes API with Query parameters syntax and examples

Nestjs provides multiple decorators to read query parameters.

For this example, Define static services that return Employee of objects,

The employee object is an interface(employee.ts)

export interface Employee {
  id: number;
  name: string;
  salary: number;
}

EmployeeService.ts returns Employee[] types as given below

import { Injectable } from "@nestjs/common";
import { Employee } from "./employee";

@Injectable()
export class EmployeeService {
  public getEmployees(): Employee[] {
    const arr: Employee[] = [
      { id: 1, name: "john", salary: 5000 },
      { id: 2, name: "victor", salary: 15000 },
      { id: 3, name: "eric", salary: 25000 },
    ];
    return arr;
  }
}

And the controller class

import { Controller, Get, Param, Query } from "@nestjs/common";
import { Employee } from "./employee";
import { EmployeeService } from "./employee.service";

@Controller("api")
export class EmployeeController {
  constructor(private readonly employeeService: EmployeeService) {}
  @Get("employees/")
  getEmployees(): Employee[] {
    return this.employeeService.getEmployees();
  }
}

api/employees with Request=GET returns all employees.

Let’s see how to read path and query parameters.

  • Request path parameters: REST Request URI contains Path arameters as given belwo
/api/employees/:id
/api/employees/:id/:salary

:id is a request path parameter replaced with a value while sending a request. Examples are /api/employees/1, /api/employees/john.

  • Request Query Parameters: query strings are key and value pairs are added to the request query. REST API contains Query params in URL to add pagination parameters(total,pages,limit) and filtering resources. Query parameters are appended to API Url with ?
/api/employees?name=john
/api/employees?start=1&size=10

Nestjs Request Path Parameters examples

nestjs provides multiple ways to read Request Path parameters.It is equavalent to req.params in ExpressionJS

  • @Param decorator that matches path names in the Request URL.
  • @Reqdecorator with the express Request object

import Param into the controller using the below line of code

import { Param } from '@nestjs/common';

Define Controller method with @Get decorator string employees/:id

@Get('employees/:id')
getProduct(@Param('id') id): Employee[]

And the Controller method is declared with @Param(pathparameter) followed by a variable. id read the path parameter and stores it under it.

It match all the below routes

/api/employees/1
/api/employees/4str

Define Controller method with @Get decorator string employees/:id

@Get('employees/:id')
getProduct(@Param('id') id): Employee[]

And the Controller method is declared with @Param(pathparameter) followed by a variable. id read the path parameter and stores it under it.

Here is an example

 @Get('employees/:id')
    getProduct(@Param('id') id): Employee[] {
        const emps = this.employeeService.getEmployees();
        let filterEmps = emps.filter(emp => {
            return emp.id == id
        });
        return filterEmps;
    }

As you can see above, we have defined an API Routes (api/employees/1) that only returns employees matched with id.

[{"id":1,"name":"john","salary":5000}]

The same thing we can rewrite using @Req decorator, Here request object holds request path parameter, Can be retrieved using either req.params.pathname or req.params[pathname] syntax.

import { Req } from '@nestjs/common';
import { Request } from 'express';
   @Get('employees/:id')
    getProduct(@Req() req: Request): Employee[] {
        const id=req.params.id // or equal to req.params["id"]

Nestjs Read Query Parameters

nestjs provides multiple ways to read Request Query parameters.It is equavalent to req.query in ExpressionJS

  • @Query decorator that matches path names in the Request URL.
  • @Req decorator with the express Request object

import Query into the controller using the below line of code

import { Query } from '@nestjs/common';

Define Controller method with @Get decorator string employees/:id

@Get('employees?')
getProductByName(@Query('name') name: string): Employee[]

And the Controller method is declared with @Query('name') name: string followed by a variable. name is a variable used to store query parameters.

It matches all below routes

/api/employees?name=john
/api/employees?name=ram

And the Controller method is declared with @Param(pathparameter) followed by a variable. id read the path parameter and stores it under it.

Here is an example

 @Get('employees/:id')
getProductByName(@Query('name') name: string): Employee[]
        const emps = this.employeeService.getEmployees();
        let filterEmps = emps.filter(emp => {
            return emp.name == name
        });
        return filterEmps;
    }

As you can see above, we have defined an API Routes (api/employees?name=john) that only returns employees matched with id.

[{"id":1,"name":"john","salary":5000}]

The same thing we can rewrite using @Req decorator, Here request object holds request path parameter, which Can be retrieved using either req.query.name or req.query[name] syntax.

import { Req } from '@nestjs/common';
import { Request } from 'express';
   @Get('employees/:id')
    getProductByName(@Req() req: Request): Employee[] {
        const id=req.query.name // or equal to req.query["id"]

how to use optional url parameters with NestjS

Routes in NestJS can have optional URL paths.

You can use query parameters for optional parameters.

Added ? symbol to parameters of a method in a controller. @Query(‘name’) name?: string contains name is optional query parameter.

Clients can call API(employees/:id) with or without id parameter

 @Get('employees/:id')
getProductByName(@Query('name') name?: string): Employee[]
        const emps = this.employeeService.getEmployees();
        let filterEmps = emps.filter(emp => {
            return emp.name == name
        });
        return filterEmps;
    }