0
0
Spring Bootframework~30 mins

Handling path variables and query params together in Spring Boot - Mini Project: Build & Apply

Choose your learning style9 modes available
Handling path variables and query params together in Spring Boot
📖 Scenario: You are building a simple Spring Boot web service for a bookstore. You want to create an endpoint that takes a book category as a path variable and an optional filter as a query parameter.This will help users get books from a specific category and optionally filter them by author name.
🎯 Goal: Build a Spring Boot controller with a method that handles a path variable category and an optional query parameter author. The method should return a string message showing the received category and author filter.
📋 What You'll Learn
Create a Spring Boot controller class named BookController
Add a GET mapping method named getBooksByCategory
Use @PathVariable to get the category from the URL path
Use @RequestParam to get the optional author query parameter with default value "all"
Return a string message showing the category and author filter values
💡 Why This Matters
🌍 Real World
Web services often need to get data from both the URL path and query parameters to filter or customize responses.
💼 Career
Understanding how to handle path variables and query parameters is essential for backend developers building REST APIs with Spring Boot.
Progress0 / 4 steps
1
Create the controller class and method signature
Create a public class named BookController annotated with @RestController. Inside it, create a public method named getBooksByCategory that returns a String. Add a @GetMapping annotation with the path "/books/{category}".
Spring Boot
Need a hint?

Use @RestController on the class. Use @GetMapping("/books/{category}") on the method. The method should return a String.

2
Add the path variable parameter
Modify the getBooksByCategory method to accept a String parameter named category annotated with @PathVariable.
Spring Boot
Need a hint?

Add @PathVariable String category as a parameter to the method.

3
Add the optional query parameter
Add a second parameter to getBooksByCategory named author of type String. Annotate it with @RequestParam with required = false and defaultValue = "all".
Spring Boot
Need a hint?

Use @RequestParam(required = false, defaultValue = "all") String author as the second parameter.

4
Return a message showing category and author
In the getBooksByCategory method, return a string formatted as "Category: {category}, Author filter: {author}" using string concatenation or String.format.
Spring Boot
Need a hint?

Use return String.format("Category: %s, Author filter: %s", category, author); to create the message.