@RequestParam
- The @RequestParam is one of the powerful annotation in Spring Boot.
- This annotation enables the Spring Boot framework to extract input data passed through the HTTP URL or passed as a query.
- Additionally, when a parameter is not specified, the method parameter can be bound to null.
- Below, we provide a simple example along with a related output image.
Example:
Now, we created one more API in the MyController class called “users”.
- For this API, we created one method called “getUser”, which takes one argument value as input, namely the user ID value, using the @RequestParam annotation in Spring Boot.
- Now, open Postman and hit the API to get the output.
- Below, we provide an image of the output.
- Additionally, we used the same domain object for this API, and this API supports only the GET method.
http://localhost:8080/users?id=1
package com.app;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyController {
// Define a method to handle GET requests to the "/users" endpoint
@GetMapping("/users")
// Method to retrieve user details based on the provided user ID parameter
public ResponseEntity<String> getUser(@RequestParam("id") Long userId) {
// Return a ResponseEntity with the user details for the specified user ID
return ResponseEntity.ok("User details for ID " + userId);
}
}
- The above code defines a Spring REST controller named
MyController
. - It contains a method
getUser()
annotated with@GetMapping
to handle GET requests to the “/users” endpoint. - The method takes a
userId
parameter annotated with@RequestParam
to retrieve user details based on the provided user ID. - Finally, it returns a ResponseEntity with the user details for the specified user ID.
Output:
Once the logic is developed, we run this project as a Spring Boot App. Now, we open Postman to test the API endpoint. Upon testing, we received the following output.
Difference between @RequestBody and @RequestParam
In Spring Boot, the @RequestBody is used for binding the HTTP request body to a parameter in a controller method and it is typically used when we expect the client to send data in the request body when submitting a form or sending JSON data. The @RequestParam is one of the powerful full annotations in Spring Boot. This annotation can enable the Spring Boot framework to extract input data passed through an HTTP URL or passed as a query.
In this article, we will learn about @RequestBody vs @RequestParam annotation.
Contact Us