Table of Contents
- Introduction
- Path Variables in Spring Boot
- Query Parameters in Spring Boot
- RequestBody in Spring Boot
- Combining Path Variables, Query Parameters, and RequestBody
- Conclusion
1. Introduction
In RESTful web services, handling incoming data from requests is essential to performing operations on resources. In Spring Boot, you can handle dynamic and static data passed through HTTP requests by using Path Variables, Query Parameters, and RequestBody annotations. These annotations allow you to extract and process data from the URL or body of the request, facilitating communication between the client and server.
In this module, we will go over each of these techniques in detail, showcasing how to extract data from the request and use it effectively within the controller methods.
2. Path Variables in Spring Boot
Path variables are used to capture dynamic values from the URI of a request. These are often used to identify specific resources, such as an individual user or product by its ID.
Example:
javaCopyEdit@RestController
@RequestMapping("/api/users")
public class UserController {
@GetMapping("/{userId}")
public String getUserById(@PathVariable("userId") Long userId) {
return "Fetching user with ID: " + userId;
}
}
In this example:
@GetMapping("/{userId}")
: Maps a GET request with a dynamicuserId
value in the URL.@PathVariable("userId")
: Extracts theuserId
from the URL and maps it to the method parameteruserId
.
When a request is made to GET /api/users/123
, the userId
will be extracted as 123
, and the method will return the message: “Fetching user with ID: 123”.
Path Variables in Multiple Places:
You can also use multiple path variables in a single URI.
javaCopyEdit@GetMapping("/{userId}/orders/{orderId}")
public String getOrderDetails(@PathVariable Long userId, @PathVariable Long orderId) {
return "Fetching order " + orderId + " for user " + userId;
}
Here, two path variables userId
and orderId
are extracted from the URI.
3. Query Parameters in Spring Boot
Query parameters are passed in the URL after the ?
symbol and are typically used to filter or refine the data being requested. These parameters are optional and can appear multiple times in a URL.
Example:
javaCopyEdit@RestController
@RequestMapping("/api/products")
public class ProductController {
@GetMapping
public String searchProducts(@RequestParam String category, @RequestParam Double price) {
return "Searching for products in category " + category + " with price " + price;
}
}
In this example:
@RequestParam
: Used to extract query parameters from the URL. The parameterscategory
andprice
are passed as query parameters.- If the client makes a request like
GET /api/products?category=electronics&price=500
, the method will return: “Searching for products in category electronics with price 500”.
Optional Query Parameters:
You can also make query parameters optional by providing default values:
javaCopyEdit@GetMapping
public String searchProducts(@RequestParam(defaultValue = "all") String category) {
return "Searching for products in category: " + category;
}
In this case, if the category
query parameter is not provided, the method will use the default value all
.
4. RequestBody in Spring Boot
The @RequestBody
annotation is used to extract data from the body of an HTTP request. This is particularly useful when clients send complex data structures (such as JSON or XML) in the body of a POST or PUT request.
Example:
javaCopyEdit@RestController
@RequestMapping("/api/users")
public class UserController {
@PostMapping
public String createUser(@RequestBody User user) {
return "User created: " + user.getName();
}
}
In this example:
@RequestBody
: Tells Spring to bind the body of the request to theUser
object. The data sent in the body (in JSON format) will be automatically deserialized into theUser
object.- If the client sends a POST request with the following JSON body: jsonCopyEdit
{ "name": "John Doe", "email": "[email protected]" }
TheUser
object will be populated with this data, and the response will be: “User created: John Doe”.
Spring automatically uses the Jackson library to convert the JSON data to a Java object and vice versa.
5. Combining Path Variables, Query Parameters, and RequestBody
In some scenarios, you may need to use a combination of path variables, query parameters, and request bodies in the same request. Spring makes it easy to handle all three types of data simultaneously.
Example:
javaCopyEdit@RestController
@RequestMapping("/api/orders")
public class OrderController {
@PostMapping("/{userId}")
public String createOrder(@PathVariable Long userId,
@RequestParam String product,
@RequestBody Order order) {
return "Order for product " + product + " created for user " + userId + ". Order details: " + order.toString();
}
}
In this example:
@PathVariable Long userId
: Extracts the user ID from the URI.@RequestParam String product
: Extracts theproduct
query parameter from the URL.@RequestBody Order order
: Extracts the request body and binds it to anOrder
object.
For a request like:
bashCopyEditPOST /api/orders/1?product=laptop
Body:
{
"quantity": 2,
"shippingAddress": "123 Main St"
}
The method will return: “Order for product laptop created for user 1. Order details: Order[quantity=2, shippingAddress=123 Main St]”.
6. Conclusion
In this module, we have explored how to handle different types of incoming data in Spring Boot controllers:
- Path Variables are used to extract dynamic values from the URL, typically used for identifying specific resources.
- Query Parameters are used for filtering or refining data with optional parameters.
- RequestBody is used to capture data sent in the body of the HTTP request, typically in JSON format.
By using these annotations in combination, you can create highly flexible and dynamic RESTful APIs that can handle various types of input from clients.