Spring Boot API: @PathVariable vs @RequestParam

@𝗥𝗲𝗾𝘂𝗲𝘀𝘁𝗣𝗮𝗿𝗮𝗺 𝘃𝘀 @𝗣𝗮𝘁𝗵𝗩𝗮𝗿𝗶𝗮𝗯𝗹𝗲 — know when to use what Many APIs work even when we mix them up. But clean APIs come from 𝗰𝗹𝗲𝗮𝗿 𝗶𝗻𝘁𝗲𝗻𝘁, not luck. Let’s break it down 👇 𝗪𝗵𝗮𝘁 @𝗣𝗮𝘁𝗵𝗩𝗮𝗿𝗶𝗮𝗯𝗹𝗲 𝗶𝘀 𝘂𝘀𝗲𝗱 𝗳𝗼𝗿 @PathVariable is used when the value is part of the resource identity. Example: GET /users/42 Use cases: • Fetching a specific resource • Identifying entities (id, orderId, productId) • Mandatory by nature 👉 Think: 𝗪𝗵𝗼 𝗼𝗿 𝘄𝗵𝗮𝘁 𝗮𝗺 𝗜 𝗮𝗰𝗰𝗲𝘀𝘀𝗶𝗻𝗴? 𝗪𝗵𝗮𝘁 @𝗥𝗲𝗾𝘂𝗲𝘀𝘁𝗣𝗮𝗿𝗮𝗺 𝗶𝘀 𝘂𝘀𝗲𝗱 𝗳𝗼𝗿 @RequestParam is used for additional information sent to the API. Example: GET /users?status=ACTIVE&page=1 Use cases: • Filtering • Sorting • Pagination • Optional parameters 👉 Think: 𝗛𝗼𝘄 𝗱𝗼 𝗜 𝘄𝗮𝗻𝘁 𝘁𝗵𝗲 𝗱𝗮𝘁𝗮? 𝗞𝗲𝘆 𝗱𝗶𝗳𝗳𝗲𝗿𝗲𝗻𝗰𝗲 𝗶𝗻 𝗼𝗻𝗲 𝗹𝗶𝗻𝗲 @PathVariable → identifies the resource @RequestParam → modifies the request 𝗖𝗼𝗺𝗺𝗼𝗻 𝗺𝗶𝘀𝘁𝗮𝗸𝗲 ❌ Using @RequestParam for IDs: /user?id=42 It works… but it hides the meaning of the API. ✅ Cleaner version: /users/42 Rule I follow now: If the value: • Defines what resource → use @PathVariable • Defines how to fetch → use @RequestParam Clear URLs = 𝗯𝗲𝘁𝘁𝗲𝗿 𝗔𝗣𝗜𝘀. Which one do you use more in your projects? 👇 #SpringBoot #RequestParam #PathVariable #RESTAPI #BackendDevelopment #Java #LearningInPublic

  • graphical user interface

To view or add a comment, sign in

Explore content categories