Monday, 12 May 2025

Query Parameter / @RequestParam in springboot

While developing web application using Spring Boot, a @RequestParam (commonly referred to as query param) is used to extract query parameters from the URL in a REST API.

1. What is a Query Parameter?

A query parameter is part of the URL that comes after the ? symbol and is usually used to pass data to the server. Example:

GET /api/products?category=electronics&sort=price

Here, category and sort are query parameters.

2. Using @RequestParam in Spring Boot

@GetMapping("/greet")
public String greet(@RequestParam String name) {
    return "Hello, " + name;
}

Call : GET /greet?name=John

Response: Hello, John

3. Optional Query Param with Default Value

@GetMapping("/greet")
public String greet(@RequestParam(defaultValue = "Guest") String name) {
    return "Hello, " + name;
}

Call: GET /greet

Response: Hello, Guest

4. Optional Query Param with required = false

@GetMapping("/greet")
public String greet(@RequestParam(required = false) String name) {
    if (name == null) return "Hello, Guest";
    return "Hello, " + name;
}

5. Multiple Query Params

@GetMapping("/search")
public String search(
    @RequestParam String keyword,
    @RequestParam(required = false) String sortBy
) {
    return "Searching for " + keyword + " sorted by " + sortBy;
}

Call: GET /search?keyword=laptop&sortBy=price


No comments:

Post a Comment