Spring Boot PathVariable vs RequestParam

Spring Boot DAY 21 –PathVariable vs RequestParam Understanding the difference between @PathVariable and @RequestParam is very important while building REST APIs 👇 Both are used to extract data from the URL, but they serve different purposes. --- 🔹 1️⃣ @PathVariable ✔ Used to extract values from the URL path ✔ Part of the resource identity ✔ Mandatory by default ✅ Example URL: /users/10 ✅ Code Example: java @GetMapping("/users/{id}") public String getUser(@PathVariable int id) { return "User ID: " + id; } 👉 Here, 10 is part of the URL path. 👉 It represents a specific resource (User with ID 10). 📌 Mostly used when: Fetching single record Updating a specific resource Deleting a specific resource --- 🔹 2️⃣ @RequestParam ✔ Used to extract values from query parameters ✔ Used for filtering, sorting, searching ✔ Can be optional ✅ Example URL: /users?id=10 ✅ Code Example: java @GetMapping("/users") public String getUserById(@RequestParam int id) { return "User ID: " + id; } 👉 Here, id=10 is passed as a query parameter. 👉 Mostly used for filtering or optional data. 📌 Example: /users?city=Nashik /users?page=1&size=5 /users?sort=asc 💡 When to Use What? 👉 Use @PathVariable when the value is required to uniquely identify a resource. 👉 Use @RequestParam when passing optional filters or additional parameters. 🎯 Interview Tip: If the data changes the identity of the resource → use PathVariable If the data modifies how results are returned → use RequestParam

  • graphical user interface, text, application

Nice summary. These two annotations look similar at first, but they serve very different purposes. PathVariable is about addressing a specific resource, RequestParam is about shaping the response. Clean APIs start with understanding this difference.

To view or add a comment, sign in

Explore content categories