Spring Framework
Java
@RequestBody
@RequestParam
Web Development

What is difference between RequestBody and RequestParam?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

In the realm of Spring Framework, particularly in building RESTful web services, two commonly used annotations are @RequestBody and @RequestParam. Understanding their differences is crucial for developers as they play distinct roles in mapping HTTP requests to controller methods. This article explores these annotations, detailing their functions, usage scenarios, and key differences.

@RequestBody

Description

The @RequestBody annotation binds HTTP request body to a method parameter. It is typically used in RESTful services when a client sends data that should be processed by a server. JSON and XML are commonly employed data formats in these scenarios. The Spring framework uses the HttpMessageConverter to convert the raw request body into a desired Java object.

Example

Here's a simple example to illustrate @RequestBody use:

java
1@RestController
2public class UserController {
3
4    @PostMapping("/users")
5    public ResponseEntity<User> createUser(@RequestBody User user) {
6        // Process the user object
7        return new ResponseEntity<>(user, HttpStatus.CREATED);
8    }
9}

In this example, when a POST request is made to /users with a JSON payload representing a User object, Spring converts this JSON into a User instance using the registered HttpMessageConverter.

Use Cases

  • Handling POST requests with data in JSON, XML or any other format that can be converted into a Java object.
  • Receiving complex data structures or nested objects.

@RequestParam

Description

The @RequestParam annotation is used to extract query parameters, form parameters, or specific URI path variables from the URL. It allows for retrieval of simple values from the request, such as String, int, or boolean.

Example

java
1@RestController
2public class SearchController {
3
4    @GetMapping("/search")
5    public ResponseEntity<String> search(@RequestParam String query) {
6        // Process the search query
7        return new ResponseEntity<>("Searching for: " + query, HttpStatus.OK);
8    }
9}

In this example, a GET request to /search?query=spring would extract the query parameter and process it within the method.

Use Cases

  • Extracting simple, flat data from the URL's query string.
  • Handling optional parameters using default values or checking inclusion.

Key Differences

Feature@RequestBody@RequestParam
PurposeBind request body to a method parameter.Bind query parameters to method parameters.
Data SourceHTTP request body.Query string or form data in URL.
Accepted Data FormatSuitable for JSON, XML, or other complex data formats.Typically plain text, numbers, or simple data types.
Conversion MethodUses HttpMessageConverter for data binding.Performed by Spring's data binder.
Use Case ExamplesReceiving JSON objects that need conversion into Java POJOs.Extracting singular data elements such as String, int, etc.
MethodPrimarily for POST, PUT, and PATCH requests.Works with GET requests but can also handle POST forms.
Complexity HandlingSuitable for complex nested data structures.Best used for flat or simple data input.
Optional ParametersParameter validation required; null objects may throw exceptions.Can handle optional params easily with default values.

Additional Considerations

Handling Optional Parameters

For @RequestParam, it is a common practice to design APIs with optional query parameters. Developers can specify default values in the method signature, facilitating backward compatibility when APIs evolve.

java
1@GetMapping("/products")
2public ResponseEntity<String> getProducts(@RequestParam(defaultValue = "10") int limit) {
3    return new ResponseEntity<>("Number of products: " + limit, HttpStatus.OK);
4}

Validation

Data bound from HTTP requests using @RequestBody often requires validation to ensure the integrity and correctness of incoming data. Spring offers the @Valid and @Validated annotations to facilitate this validation.

java
1@PostMapping("/createUser")
2public ResponseEntity<User> createUser(@Valid @RequestBody User user) {
3    // If validation fails, an appropriate error is returned
4    return new ResponseEntity<>(user, HttpStatus.CREATED);
5}

Conclusion

In summary, the choice between @RequestBody and @RequestParam is determined by the nature and source of the data being handled. @RequestBody is indispensable for parsing and handling structured data from the request body, while @RequestParam excels in extracting simple scalars from URLs. Understanding these distinctions allows developers to write cleaner, more effective code tailored to the demands of incoming HTTP requests.


Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.