Params in Spring Boot : Path Variables, Request and Query Params

🌐 What Are Parameters in Web Requests?

When building REST APIs or web apps, parameters help you pass data from the client (browser or app) to the server (your Spring Boot backend). In Spring Boot, you can access these parameters using:

  • Path Variables
  • Request Parameters
  • Query Parameters (synonym for Request Params, commonly used term)

They all serve different purposes. Let’s break the Params in Spring Boot down.

Params in Spring Boot

πŸ”— 1. Path Variables (@PathVariable)

βœ… Use case:

When the value is part of the URL path β€” typically identifying a specific resource.

πŸ“¦ Example URL:

GET /products/42

πŸ“„ Controller Example:

βœ… Output:

Product ID: 42

πŸ” Notes:

  • Use when identifying a specific resource.
  • Clear and readable RESTful URL.

🧾 2. Request Parameters (@RequestParam)

βœ… Use case:

When the data is passed as key-value pairs after a ? in the URL.

πŸ“¦ Example URL:

GET /products/search?name=keyboard&limit=10

πŸ“„ Controller Example:

βœ… Output:

Searching for: keyboard, Limit: 10

πŸ” Notes:

  • Great for optional or filtering parameters.
  • Supports default values and required flags.

🧡 3. Query Parameters (Same as Request Params)

βœ… Query params = Request params

They are just different names for the same thing. Some developers use β€œquery params” for readability.

GET /users?sort=asc&page=2

These are all accessed using @RequestParam.

πŸ”„ Combining Both: Path + Request Params

You can use both together in the same request:

πŸ“¦ Example URL:

GET /orders/55?includeDetails=true

πŸ“„ Controller:

πŸ›‘οΈ Making Params Optional

Or use a default value:

🚫 Common Mistakes to Avoid

MistakeWhy It’s a Problem
Forgetting @PathVariable or @RequestParamSpring won’t map values correctly
Mismatched variable namesMust match or explicitly specify the param name
Assuming query param is requiredWill throw an error unless marked optional
Putting sensitive data in URLUse POST body for credentials, tokens, etc.

πŸ§ͺ Real-World Examples

Get user by ID:

Filter users by role:

Pagination:

βœ… Summary

TypeAnnotationExampleUse Case
Path Variable@PathVariable/users/10Resource identification
Request/Query Param@RequestParam/users?role=adminFiltering, searching, options
Optional Param@RequestParam(required = false)/usersOptional behavior

Mastering Params in Spring Boot is essential for building clean and effective REST APIs.

πŸ“˜ External References