Introduction
In this chapter, we will explore how to create a Spring Boot REST API that uses the @RequestParam
annotation to handle query parameters. Query parameters are a common way to pass data to REST endpoints, especially for filtering, sorting, or paginating results. We will continue from the previous chapters and extend our StudentController
to demonstrate the use of @RequestParam
.
@RequestParam Annotation
What is @RequestParam?
The @RequestParam
annotation in Spring Boot is used to extract query parameters from the URL and bind them to method parameters in a controller. It helps in mapping specific query parameters in the URL to method parameters, allowing for more flexible and dynamic request handling.
How @RequestParam Works
When a client sends a request to a specific URL with query parameters, the @RequestParam
annotation extracts these parameters and assigns them to method parameters. This is useful for accessing and processing additional information provided in the query string of the URL.
Key Features of @RequestParam
- Binding Query Parameters to Method Parameters: It directly binds query parameters from the URL to the method parameters in the controller.
- Default Values: You can specify default values for query parameters to handle cases where the parameter might not be provided in the URL. This ensures that your method can handle requests gracefully, even if some parameters are missing.
- Optional Parameters: You can mark parameters as optional, allowing the method to be called even if the parameter is not present in the query string. This adds flexibility to your request handling.
- Type Conversion: Spring Boot automatically converts query parameters from strings to the appropriate data type for the method parameter, making it easier to work with various types of data.
Implementation: Update the Controller Class
In the src/main/java/com/company/restapi/controller
directory, open the StudentController
class and update it to include new endpoints that accept request parameters.
REST API with Single Request Parameter
@GetMapping("/students/last-name")
public List<Student> getStudentsByLastName(@RequestParam(required = false) String lastName) {
if (lastName == null) {
return students;
}
return students.stream()
.filter(student -> student.getLastName().equalsIgnoreCase(lastName))
.collect(Collectors.toList());
}
Explanation
@GetMapping("/students")
: This annotation maps HTTP GET requests to the/students
URL to thegetStudentsByLastName
method.@RequestParam(required = false) String lastName
: This annotation binds the value of thelastName
query parameter to thelastName
parameter in the method. The parameter is optional (i.e., not required).- Method Logic: If the
lastName
parameter is not provided (i.e.,null
), the method returns the full list of students. If thelastName
parameter is provided, the method filters the list of students to include only those whose last name matches the provided value.
REST API with Multiple Request Parameters
@GetMapping("/students/filter")
public List<Student> getStudentsByLastNameAndEmail(@RequestParam(required = false) String lastName,
@RequestParam(required = false) String email) {
return students.stream()
.filter(student -> (lastName == null || student.getLastName().equalsIgnoreCase(lastName)) &&
(email == null || student.getEmail().equalsIgnoreCase(email)))
.collect(Collectors.toList());
}
Explanation
@GetMapping("/students/filter")
: This annotation maps HTTP GET requests to the/students/filter
URL to thegetStudentsByLastNameAndEmail
method.@RequestParam(required = false) String lastName, @RequestParam(required = false) String email
: These annotations bind the values of thelastName
andemail
query parameters to the respective parameters in the method. Both parameters are optional.- Method Logic: The method filters the list of students based on the provided
lastName
andemail
parameters. If a parameter is not provided, it is ignored in the filtering process.
REST API with Default Values for Request Parameters
@GetMapping("/students/default")
public List<Student> getStudentsWithDefault(@RequestParam(defaultValue = "Doe") String lastName,
@RequestParam(defaultValue = "example@example.com") String email) {
return students.stream()
.filter(student -> student.getLastName().equalsIgnoreCase(lastName) &&
student.getEmail().equalsIgnoreCase(email))
.collect(Collectors.toList());
}
Explanation
@GetMapping("/students/default")
: This annotation maps HTTP GET requests to the/students/default
URL to thegetStudentsWithDefault
method.@RequestParam(defaultValue = "Doe") String lastName, @RequestParam(defaultValue = "example@example.com") String email
: These annotations bind the values of thelastName
andemail
query parameters to the respective parameters in the method. If the parameters are not provided in the request, the default values (“Doe” and “example@example.com”) are used.- Method Logic: The method filters the list of students based on the provided
lastName
andemail
parameters, or the default values if the parameters are not provided.
Full Updated Controller Class
Here is the full updated StudentController
class:
package com.company.restapi.controller;
import com.company.restapi.model.Student;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
@RestController
public class StudentController {
private List<Student> students = Arrays.asList(
new Student(1L, "Ramesh", "Fadatare", "ramesh.fadatare@example.com"),
new Student(2L, "Suresh", "Kumar", "suresh.kumar@example.com"),
new Student(3L, "Mahesh", "Yadav", "mahesh.yadav@example.com")
);
@GetMapping("/student")
public Student getStudent() {
return new Student(1L, "Ramesh", "Fadatare", "ramesh.fadatare@example.com");
}
@GetMapping("/students")
public List<Student> getStudentsByLastName(@RequestParam(required = false) String lastName) {
if (lastName == null) {
return students;
}
return students.stream()
.filter(student -> student.getLastName().equalsIgnoreCase(lastName))
.collect(Collectors.toList());
}
@GetMapping("/students/{id}")
public Student getStudentById(@PathVariable Long id) {
return students.stream()
.filter(student -> student.getId().equals(id))
.findFirst()
.orElse(null);
}
@GetMapping("/students/{id}/{lastName}")
public Student getStudentByIdAndLastName(@PathVariable Long id, @PathVariable String lastName) {
return students.stream()
.filter(student -> student.getId().equals(id) && student.getLastName().equalsIgnoreCase(lastName))
.findFirst()
.orElse(null);
}
@GetMapping("/students/filter")
public List<Student> getStudentsByLastNameAndEmail(@RequestParam(required = false) String lastName,
@RequestParam(required = false) String email) {
return students.stream()
.filter(student -> (lastName == null || student.getLastName().equalsIgnoreCase(lastName)) &&
(email == null || student.getEmail().equalsIgnoreCase(email)))
.collect(Collectors.toList());
}
@GetMapping("/students/default")
public List<Student> getStudentsWithDefault(@RequestParam(defaultValue = "Doe") String lastName,
@RequestParam(defaultValue = "example@example.com") String email) {
return students.stream()
.filter(student -> student.getLastName().equalsIgnoreCase(lastName) &&
student.getEmail().equalsIgnoreCase(email))
.collect(Collectors.toList());
}
}
Running the Application
Step 2: Run Your Spring Boot Application
- Open Application Class:
- Ensure that the main application class (annotated with
@SpringBootApplication
) is open.
- Ensure that the main application class (annotated with
- Run the Application:
- In IntelliJ IDEA, right-click the main application class and select “Run ‘SpringbootRestApiApplication'”.
- Alternatively, open a terminal, navigate to the project directory, and run
mvn spring-boot:run
.
Step 3: Test Each REST API
- Single Request Parameter:
- Request:
GET http://localhost:8080/students/last-name?lastName=Kumar
- Response:
- Request:
- Multiple Request Parameters:
- Request:
GET http://localhost:8080/students/filter?lastName=Yadav&email=mahesh.yadav@example.com
- Response:
- Request:
- Request Parameters with Default Values:
- Request with Provided Values:
GET http://localhost:8080/students/default?lastName=Fadatare&email=ramesh.fadatare@example.com
- Response:
- Request with Provided Values:
- Request with Default Values:
GET http://localhost:8080/students/default
- Response:
Conclusion
In this chapter, we learned how to use the @RequestParam
annotation in Spring Boot to create REST APIs that handle single and multiple query parameters, as well as query parameters with default values. We updated the StudentController
class to include these use cases and tested each endpoint to verify their functionality. This demonstrates the flexibility and power of Spring Boot in handling dynamic query parameters for RESTful web services.