DEV Community

realNameHidden
realNameHidden

Posted on

How do you handle optional query parameters in Spring Boot?

Introduction

Imagine you’re browsing an online store. Sometimes you filter by category, sometimes you don’t. Sometimes you sort by price, sometimes you just want to see everything.

You don’t expect the website to break just because you didn’t apply a filter, right?

That’s exactly how optional query parameters should work in APIs. Clients should be able to call the same endpoint with or without extra options, and your application should respond gracefully.

In this blog, you’ll learn how to handle optional query parameters in Spring Boot, explained in simple terms with real-world analogies and end-to-end Java 21 examples.


Core Concepts

What Are Optional Query Parameters?

Optional query parameters are URL parameters that:

  • May or may not be present
  • Change the behavior of an API without being mandatory

Example:


/products
/products?category=laptop
/products?category=laptop&sort=price

Enter fullscreen mode Exit fullscreen mode

🧠 Analogy:

Think of ordering coffee ☕.

  • Coffee is mandatory
  • Sugar and milk are optional You still get coffee even if you skip the extras.

How Spring Boot Supports Optional Query Parameters

Spring Boot makes this easy using:

  • @RequestParam(required = false)
  • @RequestParam(defaultValue = "...")
  • Optional<T> (Java-friendly approach)

These tools help you build flexible and safe APIs.


Why Optional Parameters Matter

✅ Prevent unnecessary 400 BAD_REQUEST errors

✅ Improve API usability

✅ Support backward compatibility

✅ Reduce the need for multiple endpoints


Code Examples (End-to-End)


✅ Example 1: Optional Query Parameters Using required = false

Use Case

Search users with an optional role filter.


Controller Code

package com.example.demo.controller;

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

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

    /**
     * Example URLs:
     * /users
     * /users?role=admin
     */
    @GetMapping
    public String getUsers(
            @RequestParam(required = false) String role) {

        if (role == null) {
            return "Fetching all users";
        }

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

How This Works

Request Result
/users Fetch all users
/users?role=admin Fetch admin users

✔ No errors
✔ Clean logic
✔ Simple to understand


✅ Example 2: Optional Query Parameters with Default Values (Production-Ready)

Use Case

Paginated product search with optional filters.


Controller Code

package com.example.demo.controller;

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

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

    /**
     * Example URLs:
     * /products
     * /products?category=laptop
     * /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 Output
/products category=null, page=0, size=20
/products?category=laptop page=0, size=20
/products?page=2&size=5 category=null

✔ Optional params handled safely
✔ Defaults prevent runtime errors
✔ Ideal for real-world APIs


🧠 Bonus: Using Optional<T> for Cleaner Code

@GetMapping("/search")
public String search(
        @RequestParam Optional<String> keyword) {

    return keyword
            .map(k -> "Searching for keyword=" + k)
            .orElse("Fetching all results");
}
Enter fullscreen mode Exit fullscreen mode

✔ Null-safe
✔ Expressive
✔ Java-friendly


Best Practices

  1. Use optional query parameters for filters, not identifiers
    IDs belong in path variables.

  2. Always set defaults for pagination parameters
    Avoid accidental client errors.

  3. Avoid null-heavy logic
    Use Optional<T> where it improves readability.

  4. Validate optional parameters when present
    Combine with @Validated and constraints like @Min.

  5. Document optional parameters clearly
    Makes APIs easier to consume.


Conclusion

Handling optional query parameters correctly is key to building flexible and user-friendly APIs.

Spring Boot gives you multiple clean options—required=false, defaultValue, and Optional<T>—so you can choose what fits your use case best.

Mastering handling optional query parameters in Spring Boot will help you write better APIs, improve client experience, and strengthen your Java programming fundamentals.


Call to Action

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

Want to explore next?

  • Validating query parameters
  • Pagination with Pageable
  • Clean API design patterns

Just ask—happy to help 🚀


🔗 Helpful Resources


Enter fullscreen mode Exit fullscreen mode

Top comments (0)