Open In App

Spring Boot – @PathVariable and @RequestParam Annotations

Last Updated : 04 Jul, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

When building RESTful APIs with Spring Boot, it’s crucial to extract data from incoming HTTP requests to process and respond accordingly. The Spring framework provides two main annotations for this purpose: @PathVariable and @RequestParam.

  • The @PathVariable annotation is used to retrieve data from the URL path. By defining placeholders in the request mapping URL, you can bind those placeholders to method parameters annotated with @PathVariable. This allows you to access dynamic values from the URL and use them in your code. For example, you can extract a user ID from a URL like /users/123 and pass it to a method that retrieves the corresponding user’s details.
  • On the other hand, the @RequestParam annotation enables you to extract data from the query parameters in the request URL. Query parameters are key-value pairs appended to the URL after a question mark (?). With @RequestParam, you can specify the name of the parameter to retrieve and bind it to a method parameter. This is useful when you need to pass additional information or filters to your API endpoints. For instance, you can extract the value of a name parameter from a URL like /users/search?name=John and use it to search for users with the given name.
  • Both @PathVariable and @RequestParam annotations simplify the process of extracting data from incoming requests in Spring Boot. They provide a clean and declarative way to access dynamic values from URLs and query parameters, making it easier to handle and process request data in your REST API endpoints.

By leveraging these annotations effectively, you can enhance the functionality of your Spring Boot applications, create more flexible APIs, and provide better user experiences by allowing clients to pass relevant data in their requests. Here’s a detailed explanation of the @PathVariable and @RequestParam annotations in Spring Boot, along with full source code examples:

Using @PathVariable

The @PathVariable annotation is used to extract data from the URL path. It allows you to define placeholders in your request mapping URL and bind those placeholders to method parameters. Let’s consider an example where you have a REST API endpoint for retrieving a user’s details by their ID:

Java




@RestController
@RequestMapping("/users")
public class UserController {
  
    @GetMapping("/{userId}")
    public ResponseEntity<User> getUserDetails(@PathVariable Long userId) {
        // Implementation to fetch user details based on the provided userId
        // ...
        return ResponseEntity.ok(user);
    }
}


In the above code, the @PathVariable annotation is used to extract the userId from the URL path. The {userId} placeholder is defined in the @GetMapping annotation’s URL mapping. The value of the {userId} placeholder will be extracted and passed as the userId method parameter. When a request is made to /users/123, the value 123 will be passed to the getUserDetails method as the userId parameter. You can then use this ID to fetch the user details from a database or any other data source.

Using @RequestParam

The @RequestParam annotation is used to extract data from the query parameters in the request URL. Query parameters are the key-value pairs that appear after the ? in a URL. Let’s consider an example where you have a REST API endpoint for searching users based on a query parameter:

Java




@RestController
@RequestMapping("/users")
public class UserController {
  
    @GetMapping("/search")
    public ResponseEntity<List<User>> searchUsers(@RequestParam("name") String name) {
        // Implementation to search users based on the provided name
        // ...
        return ResponseEntity.ok(users);
    }
}


In the above code, the @RequestParam annotation is used to extract the name parameter from the query parameters. The name parameter is specified as an argument of the @RequestParam annotation. When a request is made to /users/search?name=John, the value John will be passed to the searchUsers method as the name parameter. You can then use this parameter to perform a search operation based on the provided name.

You can also specify optional parameters by setting the required attribute of @RequestParam to false. Additionally, you can provide default values using the defaultValue attribute. Here’s an example that demonstrates how to specify optional parameters using the @RequestParam annotation in Spring Boot and provide default values using the defaultValue attribute:

Java




@RestController
@RequestMapping("/users")
public class UserController {
  
    @GetMapping("/search")
    public ResponseEntity<List<User>> searchUsers(
            @RequestParam(value = "name", required = false, defaultValue = "John") String name,
            @RequestParam(value = "age", required = false, defaultValue = "18") int age) {
          
        // Implementation to search users based on the provided name and age
        // ...
        return ResponseEntity.ok(users);
    }
}


In the above code, the searchUsers method accepts two query parameters: name and age. Both parameters are annotated with @RequestParam and have optional configurations. The name parameter is specified with required = false, indicating that it is optional. If the name parameter is not provided in the request URL, the default value “John” will be used.

The age parameter is also specified with required = false, making it optional. In addition, it has a default value of 18 specified using defaultValue = “18”. If the age parameter is not provided in the request URL, the default value of 18 will be used. Additional points to consider regarding the topic of extracting request data using @PathVariable and @RequestParam annotations in Spring Boot:

  1. Data Type Conversion: Spring Boot provides automatic data type conversion for @PathVariable and @RequestParam parameters. It can convert the incoming request data to the required data types, such as String, int, boolean, etc. If the conversion fails, it will throw an exception, allowing you to handle the error gracefully.
  2. Multiple Parameters: You can use multiple @PathVariable and @RequestParam annotations in a single method to extract multiple values from the URL path and query parameters. This allows you to retrieve and utilize multiple data points from a single request.
  3. Data Validation: You can apply validation on the extracted request data by using validation annotations from the javax.validation package or custom validation logic. This helps ensure that the provided data meets specific criteria before processing it further.
  4. Path Variable Patterns: The @PathVariable annotation supports variable patterns within the URL path. You can define placeholders with regular expressions to match specific patterns and extract the corresponding values. This can be useful for handling dynamic and complex URL structures.
  5. Query Parameter Collections: If you expect multiple values for a query parameter, you can use List or Array types for the corresponding method parameter annotated with @RequestParam. Spring Boot will automatically bind all the values to the collection parameter.
  6. Optional Path Variables: You can make path variables optional by providing a default value or using the Optional<T> type as the method parameter. This allows you to handle cases where certain path variables may or may not be present in the request.
  7. Remember to handle potential exceptions and error scenarios appropriately when extracting request data. Spring Boot provides various mechanisms, such as exception handlers, to handle and customize error responses based on your application’s requirements.

By leveraging the power of @PathVariable and @RequestParam annotations, you can effectively extract and process request data in your Spring Boot applications, making your REST API endpoints more dynamic and versatile. Here’s the full source code for a Spring Boot application that demonstrates the usage of @PathVariable and @RequestParam annotations:

Java




import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
  
import java.util.Arrays;
import java.util.List;
  
@SpringBootApplication
public class Application {
  
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
  
@RestController
@RequestMapping("/users")
class UserController {
  
    @GetMapping("/{userId}")
    public ResponseEntity<String> getUserDetails(@PathVariable Long userId) {
        // Implementation to fetch user details based on the provided userId
        String userDetails = "User details for user ID: " + userId;
        return ResponseEntity.ok(userDetails);
    }
  
    @GetMapping("/search")
    public ResponseEntity<List<String>> searchUsers(@RequestParam("name") String name) {
        // Implementation to search users based on the provided name
        List<String> users = Arrays.asList("John", "Jane", "Robert");
        return ResponseEntity.ok(users);
    }
}


Explanation

  • The Application class is the entry point for the Spring Boot application. It is annotated with @SpringBootApplication.
  • The UserController class is annotated with @RestController, indicating that it is a REST controller.
  • The base URL path for all user-related endpoints are defined using @RequestMapping(“/users”).
  • The getUserDetails method is mapped to the /{userId} URL pattern using @GetMapping(“/{userId}”). The userId path variable is extracted using @PathVariable and passed as a method parameter.
  • The searchUsers method is mapped to the /search URL pattern using @GetMapping(“/search”). The name query parameter is extracted using @RequestParam(“name”) and passed as a method parameter.
  • You can run this Spring Boot application, and it will provide two endpoints: /users/{userId} and /users/search. You can send requests to these endpoints with appropriate path variables and query parameters to see the respective data extraction in action.

Note: Make sure you have the necessary dependencies and configurations set up in your Spring Boot project to run the application successfully.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads