Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 19

Extracting Data with @PathVariable and @RequestParam

Recommended resources

Hello! Let's dive into the next part of our journey in building RESTful APIs with Spring Boot.

In our last lesson, we focused on handling data sent in the body of an HTTP request using @RequestBody. We saw how Spring, with the help of the Jackson library, automatically converts incoming JSON into your Java objects.

Today, we shift our focus from the request body to the request URL itself. An API often needs to accept parameters directly within the URL to identify specific resources or to filter and sort collections. This lesson will teach you how to extract path variables and request parameters using the @PathVariable and @RequestParam annotations. By the end, you'll have a complete understanding of how to capture client input from all parts of an HTTP request.

The Anatomy of a Dynamic URL

Before we get into the code, let's look at a typical URL for a REST API and break it down. There are two common ways to pass dynamic data in a URL:

  1. Path Variables: These are part of the URL path and are used to identify a specific resource. They feel like part of the URL's "address."
  2. Request Parameters (or Query Parameters): These appear after a question mark (?) and are used to modify the request, such as for filtering, sorting, or pagination.

The image below provides a perfect visual breakdown.

Path Variables vs. Request Parameters in Spring Boot
This image shows a URL broken down into its components. The `/101` part is a **path variable** captured by `@PathVariable`, while `type=current` and `status=active` are **request parameters** captured by `@RequestParam`.

Let's now explore how to use each of these in Spring Boot.


1. @PathVariable: Identifying a Specific Resource

The @PathVariable annotation is your tool for extracting data embedded directly in the URL's path. Its most common use is to get a unique identifier for a resource. Think of endpoints like /users/{userId} or /orders/{orderId}.

To see this in action, let's look at a clear code example.

Spring Boot - @PathVariable and @RequestParam Annotations

This article from GeeksForGeeks shows a straightforward implementation of @PathVariable. Focus on how the {userId} in the @GetMapping annotation maps to the userId method parameter.

Read the section 'Using @PathVariable'. Note the syntax: the placeholder name in the path ("{userId}") must match the variable name in the annotation (@PathVariable Long userId) if you don't specify it explicitly.

As you saw, the implementation is quite intuitive. You define a placeholder in your mapping's path with curly braces {} and then use @PathVariable to bind the value from that part of the URL to a method parameter.

Now, let's watch a video segment that shows this being implemented in a practical scenario: deleting a specific quote by its ID. Although the video uses Kotlin, the annotations and REST concepts are identical to Java.

REST Controllers & HTTP Requests - Spring Boot 4 Basics With Kotlin

This video from Philipp Lackner demonstrates using a path parameter to specify which resource to delete. This is a classic and highly appropriate use case for @PathVariable.

Watch from 17:35 to 19:15. Pay attention to how the URL for the DELETE request is structured as /quotes/{id} and how the @PathVariable annotation captures that id.

The equivalent Java code for the deleteQuote method shown in the video would look like this:

@DeleteMapping("/{id}")
public void deleteQuote(@PathVariable Long id) {
    // Logic to find the quote by 'id' and remove it from the list
    quotes.removeIf(quote -> quote.getId().equals(id));
}

This pattern is fundamental in REST API design for any action targeting a single, specific item.


2. @RequestParam: Filtering, Sorting, and Optional Data

While @PathVariable is for required identifiers, @RequestParam is used for extracting data from the query string (e.g., /search?query=spring). This makes it perfect for optional parameters, filters, and sorting controls.

Let's start with a reading that shows the basic usage and, more importantly, how to handle optional parameters and provide default values.

Spring Boot - @PathVariable and @RequestParam Annotations

This GeeksForGeeks article clearly demonstrates @RequestParam, including how to make a parameter optional and provide a default value if it's not present in the request.

Read the section 'Using @RequestParam'. Pay close attention to the use of required = false and defaultValue. This is extremely useful for creating flexible APIs.

The ability to set required = false and provide a defaultValue is a powerful feature. It allows clients to omit parameters without causing an error, making your API more robust and easier to use.

Now, let's see a practical example of implementing a search filter using @RequestParam.

REST Controllers & HTTP Requests - Spring Boot 4 Basics With Kotlin

This segment from the same Philipp Lackner video shows how to add an optional query parameter q to search for quotes containing a specific string.

Watch from 22:37 to 25:00. Observe how the endpoint can be called with or without the ?q=... parameter and how the code handles both cases.

Here is the Java equivalent of the endpoint that filters quotes:

@GetMapping
public List<QuoteDTO> getQuotes(@RequestParam(value = "q", required = false) String query) {
    if (query != null && !query.isEmpty()) {
        // If a query is provided, filter the list
        return quotes.stream()
                     .filter(quote -> quote.getContent().toLowerCase().contains(query.toLowerCase()))
                     .collect(Collectors.toList());
    } else {
        // Otherwise, return the full list
        return quotes;
    }
}

This filtering logic is a common pattern you'll implement often in backend development.

Test your understanding!

You are designing an API endpoint to fetch a list of products. The endpoint is /products. You want to allow clients to paginate the results by specifying a page number and a limit for the number of items per page.
For example: /products?page=2&limit=25.

If a client doesn't provide these parameters, the API should default to page=0 and limit=10.

How would you write the method signature for this endpoint?

Show answer

The method signature would look like this:

@GetMapping("/products")
public List<Product> getProducts(
    @RequestParam(value = "page", required = false, defaultValue = "0") int page,
    @RequestParam(value = "limit", required = false, defaultValue = "10") int limit
) {
    // ... implementation to fetch products using pagination ...
    return paginatedListOfProducts;
}

This uses required = false to make the parameters optional and defaultValue to ensure page and limit always have a value, even if the client omits them.


3. @PathVariable vs. @RequestParam: When to Use Which?

Now that you've seen both annotations, let's solidify the distinction. Choosing the right one is key to designing clean, intuitive REST APIs.

This short video provides a fantastic side-by-side comparison.

@RequestParam vs @PathVariable in Spring Boot | Last-Minute Java Interview Guide

This video from Java Guides is dedicated to explaining the differences between @RequestParam and @PathVariable and the specific situations where each one shines.

Watch the entire video. It concisely covers the core differences in syntax, use case, and RESTful semantics.

To dive deeper into the nuances, the following Baeldung article is an excellent resource. It also touches on a subtle point about URL encoding that aligns with your interest in "under the hood" details.

Spring @RequestParam vs @PathVariable Annotations

This Baeldung article provides a detailed comparison with clear code examples. It also introduces an interesting difference in how the values are processed.

Read sections 2 ('Query Parameter vs URI Path') and 3 ('Encoded vs Exact Value'). Section 3 highlights that @RequestParam values are URL-decoded, while @PathVariable values are not. This is a subtle but important distinction.

Finally, this comparison table is a great reference to bookmark or save for a quick review.

Comparison of @RequestParam and @PathVariable in Spring
This table provides a comprehensive summary of the key differences between `@RequestParam` and `@PathVariable`, covering their purpose, syntax, and behavior.

Conclusion

You've now mastered the essential tools for capturing data passed in a URL. This, combined with your knowledge of @RequestBody from the previous lesson, gives you a complete toolkit for handling inputs in your Spring Boot REST controllers.

Key Takeaways:

  • @PathVariable is for extracting required values that are part of the URL path itself. It's semantically tied to identifying a specific resource. (e.g., GET /users/123).
  • @RequestParam is for extracting values from the query string. It's ideal for optional parameters used to filter, sort, or paginate a collection of resources. (e.g., GET /users?status=active).
  • You can make request parameters optional and provide defaults using @RequestParam(required = false, defaultValue = "...").

What's Next?

So far, we've focused on getting data into our API. But a well-designed API also needs to provide clear, standardized responses. In the next lesson, we will learn how to return appropriate HTTP status codes and headers using ResponseEntity. This will give you fine-grained control over your API's output, allowing you to communicate success, errors, and other states to the client precisely.