Spring Boot Parameters

Spring Boot provides a simple way to handle Path Parameters and Query Parameters using @PathVariable and @RequestParam.

Path Parameters (@PathVariable)

  • Path parameters are part of the URL (e.g., /users/{id}).
  • They are mandatory.
  • Used to identify a specific resource.
Example: Get User by ID
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/users")
public class UserController {

// ✅ Path Parameter Example
@GetMapping("/{id}")
public String getUserById(@PathVariable int id) {
return "User ID: " + id;
}
}
Test in Browser or Postman
GET http://localhost:8080/api/users/10
Response
User ID: 10

Query Parameters (@RequestParam)

  • Query parameters are appended after ? in the URL (e.g., /users?name=Alice).
  • They are optional (can have default values).
  • Used for searching, filtering, sorting.
Example: Search User by Name
@RestController
@RequestMapping("/api/users")
public class UserController {

// ✅ Query Parameter Example
@GetMapping("/search")
public String searchUser(@RequestParam String name) {
return "Searching for user: " + name;
}
}
Test in Browser or Postman
GET http://localhost:8080/api/users/search?name=Alice
Response
Searching for user: Alice

Multiple Query Parameters

  • You can pass multiple parameters using @RequestParam.
Example: Get Users with Filters
@RestController
@RequestMapping("/api/users")
public class UserController {

// ✅ Multiple Query Parameters
@GetMapping("/filter")
public String filterUsers(
@RequestParam(required = false) String name,
@RequestParam(required = false) Integer age) {

return "Filtering users by Name: " + name + ", Age: " + age;
}
}
Test with Multiple Parameters
GET http://localhost:8080/api/users/filter?name=Bob&age=25
Response
Filtering users by Name: Bob, Age: 25

Combining Path & Query Parameters

You can use both @PathVariable and @RequestParam together.

Set default values "Unknown" if parameter doesn't have city http://localhost:8080/api/user/10/details

Example: Get User Details
@RestController
@RequestMapping("/api/users")
public class UserController {

// ✅ Path + Query Parameters
@GetMapping("/{id}/details")
public String getUserDetails(
@PathVariable int id,
@RequestParam(required = false, defaultValue = "Unknown") String city) {

return "User ID: " + id + ", City: " + city;
}
}
Test the API
GET http://localhost:8080/api/users/10/details?city=NewYork
Response
User ID: 10, City: NewYork

Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.