Spring Boot REST API: @PathVariable vs @RequestParam

👉 Understanding @PathVariable vs @RequestParam While building REST APIs in Spring Boot, we often need to send data from the URL to the controller. Two common ways to do this are: ➡ @PathVariable ➡ @RequestParam 🔹 1. @PathVariable @PathVariable is used to extract values directly from the URL path. Example URL: http://localhost:8080/users/10 Example Code: @GetMapping("/users/{id}") public String getUser(@PathVariable int id) { return "User ID: " + id; } ✔ Used when the value is part of the resource path ✔ Common in RESTful APIs 🔹 2. @RequestParam @RequestParam is used to extract query parameters from the URL. Example URL: http://localhost:8080/users?id=10 Example Code: @GetMapping("/users") public String getUser(@RequestParam int id) { return "User ID: " + id; } ✔ Used for filtering, searching, or optional parameters 🧠 Simple Way to Remember 👉 PathVariable → Part of URL path 👉 RequestParam → Extra data in query #SpringBoot #Java #RestAPI #BackendDevelopment #LearningInPublic #JavaDeveloper

To view or add a comment, sign in

Explore content categories