DEV Community

realNameHidden
realNameHidden

Posted on

How Do You Read Query Parameters in Spring Boot?

Learn how to read query parameters in Spring Boot using @RequestParam with clear, beginner-friendly explanations and Java 21 end-to-end examples.


Introduction

Imagine you’re shopping online and you click a link like this:


/products?category=mobile&sort=price&page=1

Enter fullscreen mode Exit fullscreen mode

Behind the scenes, the server reads those query parameters (category, sort, page) to decide what data to return and how to return it.

In Spring Boot, reading query parameters is one of the most common tasks when building REST APIs. Whether you’re filtering products, paginating results, or toggling features, query parameters are your go-to tool.

In this blog, you’ll learn how to read query parameters in Spring Boot, using simple explanations, real-world analogies, and end-to-end Java 21 examples.


Core Concepts

What Are Query Parameters?

Query parameters are key–value pairs appended to a URL after the ? symbol.

Example:


/users?role=admin&active=true

Enter fullscreen mode Exit fullscreen mode
  • role → admin
  • active → true

🧠 Think of query parameters as options on a remote control—same TV (endpoint), different behavior based on buttons pressed.


How Spring Boot Reads Query Parameters

Spring Boot provides the @RequestParam annotation to:

  • Extract values from the URL
  • Automatically convert them to Java types
  • Handle optional and required parameters

Why Use Query Parameters?

✅ Filtering data

✅ Sorting results

✅ Pagination

✅ Feature flags

✅ Optional inputs (without changing the endpoint)


Code Examples (End-to-End)


✅ Example 1: Reading Simple Query Parameters with @RequestParam

Use Case

Fetch users filtered by role and active status.


Step 1: REST Controller

package com.example.demo.controller;

import org.springframework.web.bind.annotation.*;

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

    /**
     * Example URL:
     * /users?role=admin&active=true
     */
    @GetMapping
    public String getUsers(
            @RequestParam String role,
            @RequestParam boolean active) {

        return "Fetching users with role=" + role + ", active=" + active;
    }
}
Enter fullscreen mode Exit fullscreen mode

🔍 How It Works

URL Result
/users?role=admin&active=true ✅ Works
/users?role=admin ❌ 400 Bad Request (missing param)

By default:

  • @RequestParam is required
  • Missing values cause 400 BAD_REQUEST

✅ Example 2: Optional Query Parameters, Defaults & Pagination

Use Case

Search products with optional filters and pagination.


Step 2: REST Controller with Optional Params

package com.example.demo.controller;

import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/products")
public class ProductController {

    /**
     * Example URL:
     * /products?category=laptop&page=1&size=10
     */
    @GetMapping
    public String searchProducts(
            @RequestParam(required = false) String category,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "20") int size) {

        return String.format(
                "Searching products [category=%s, page=%d, size=%d]",
                category, page, size);
    }
}
Enter fullscreen mode Exit fullscreen mode

🔍 Behavior Explained

URL Result
/products category=null, page=0, size=20
/products?category=laptop page=0, size=20
/products?page=2&size=5 category=null

Spring Boot automatically:

  • Converts query params to Java types
  • Applies default values
  • Handles missing optional params safely

🧠 Bonus: Multiple Query Parameters as a Map

@GetMapping("/search")
public String search(@RequestParam Map<String, String> params) {
    return "Query params received: " + params;
}
Enter fullscreen mode Exit fullscreen mode

✔ Useful for dynamic filtering
✔ Common in search APIs


Best Practices

  1. Always use default values for pagination
    Avoid unexpected 400 errors.

  2. Prefer query params for optional data
    Path variables should represent mandatory identifiers.

  3. Validate query parameters
    Combine @Validated with constraints like @Min.

  4. Use meaningful parameter names
    page is better than p.

  5. Avoid too many query parameters
    Complex filters may need a request body.


Conclusion

Reading query parameters is a fundamental skill for building REST APIs with Spring Boot.

By using:

  • @RequestParam
  • Optional parameters
  • Default values

you can build flexible, user-friendly APIs that adapt to different client needs.

Mastering reading query parameters in Spring Boot will significantly improve your confidence in Java programming and help you learn Java with real-world practices.


Call to Action

💬 Have questions about query parameters or REST API design?
👇 Drop them in the comments!

Want advanced topics next?

  • Validation for query params
  • Pagination with Pageable
  • API design best practices

Just ask 🚀


🔗 Helpful Resources



Enter fullscreen mode Exit fullscreen mode

Top comments (0)