0
0
NestJSframework~30 mins

Query parameters in NestJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Handling Query Parameters in NestJS
📖 Scenario: You are building a simple NestJS API that returns a list of books. You want to allow users to filter books by genre using query parameters.
🎯 Goal: Create a NestJS controller that reads a genre query parameter from the URL and returns only books matching that genre.
📋 What You'll Learn
Create a controller with a GET route /books
Use the @Query() decorator to read the genre query parameter
Filter the list of books by the genre parameter if it is provided
Return the filtered list of books as JSON
💡 Why This Matters
🌍 Real World
APIs often need to filter data based on user input in the URL. Query parameters let users specify filters without changing the route.
💼 Career
Backend developers use query parameters to build flexible APIs that serve filtered data, improving user experience and performance.
Progress0 / 4 steps
1
Set up the books data array
Create a variable called books that is an array of objects. Each object should have title and genre properties with these exact entries: { title: 'The Hobbit', genre: 'Fantasy' }, { title: '1984', genre: 'Dystopian' }, { title: 'The Catcher in the Rye', genre: 'Classic' }.
NestJS
Need a hint?

Use const books = [ ... ] to create the array with the exact objects.

2
Create the controller and import decorators
Create a NestJS controller class called BooksController. Import Controller and Get from @nestjs/common. Add the @Controller('books') decorator above the class.
NestJS
Need a hint?

Use @Controller('books') above the class and import the decorators from @nestjs/common.

3
Add a GET method with query parameter
Inside BooksController, add a method called getBooks with the @Get() decorator. Use the @Query('genre') decorator to get the genre query parameter as a string argument. Filter the books array to only include books where book.genre === genre if genre is provided. Return the filtered array or all books if no genre is given.
NestJS
Need a hint?

Import @Query and use it to read the genre query parameter. Use filter to select matching books.

4
Export the controller and finalize
Make sure the BooksController class is exported with export class BooksController. This completes the controller setup to handle query parameters.
NestJS
Need a hint?

Use export class BooksController to make the controller available to the app.