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, the recipeId variable will take the value 123.
  • When someone requests /recipes/pizza-pepperoni, the recipeId variable will take the value pizza-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:

Java
@GetMapping("/recipes/{recipeId}")
public Recipe getRecipeById(@PathVariable Long recipeId) {
    return recipeRepository.findById(recipeId)
            .orElseThrow(() -> new IllegalArgumentException("Recipe not found"));
}

Here’s what’s happening:

  1. @GetMapping("/recipes/{recipeId}): Maps HTTP GET requests to /recipes/{recipeId}. {recipeId} is a path variable.
  2. @PathVariable Long recipeId: Binds the path variable recipeId from the URL to the method parameter.
  3. The method interacts with recipeRepository to find a recipe by its ID.
  4. If no matching recipe is found, it throws an IllegalArgumentException.

Path variables make your URLs more dynamic and informative.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal