Handling Path Variables and Query Parameters
Introduction
Welcome! In this lesson, we'll dive into Handling Path Variables and Query Parameters in Spring Boot. You've already learned how to create REST endpoints and return JSON responses. Now, we’ll extend that knowledge by exploring how to handle path variables and query parameters in your APIs.
Path variables and query parameters are crucial for passing information and filtering data in RESTful APIs. These tools will make your endpoints more dynamic and powerful. Let’s get started!
Understanding Path Variables
In previous lessons, we used hardcoded endpoints like /recipes/american-sandwich. As your application grows and you have a database with thousands of recipes, defining a separate endpoint for each recipe becomes impractical. Instead, you can use path variables, such as: /recipes/{recipeId}. Here, recipeId is a dynamic part of the URL that gets passed to your methods. For example:
- When someone requests
/recipes/123, therecipeIdvariable will take the value123. - When someone requests
/recipes/pizza-pepperoni, therecipeIdvariable will take the valuepizza-pepperoni.
You can also have paths with multiple path variables. For instance, by introducing recipe categories, you can have the following paths:
/categories/{recipeCategory}/categories/{recipeCategory}/recipes/{recipeId}
This hierarchical structure makes your API more organized and reflective of your domain model.
Path Variables Example
Imagine you have a collection of recipes, and you want to retrieve a specific recipe by its unique ID. Here’s how you can implement this in Spring Boot:
Here’s what’s happening:
@GetMapping("/recipes/{recipeId}): Maps HTTP GET requests to/recipes/{recipeId}.{recipeId}is a path variable.@PathVariable Long recipeId: Binds the path variablerecipeIdfrom the URL to the method parameter.- The method interacts with
recipeRepositoryto find a recipe by its ID. - If no matching recipe is found, it throws an
IllegalArgumentException.
Path variables make your URLs more dynamic and informative.
