Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

when should I use PathVariable and when should I use RequestParam [closed]

I understand the main difference between the two, @RequestParam is used for query parameters, and can have few more attributes, while @PathVariable has one attribute and is for a path parameter.

but I couldn't find any info about when there's a preference to use either query param or path param. I assume that in some cases in which I want a default value or some other attribute that @RequestParam has, It's probably better to use it. but is there any big difference other than that? any time that @PathVariable is preferred?

like image 333
Daniel Avatar asked Mar 12 '26 02:03

Daniel


1 Answers

It depends on your design choices, i.e. whether you want to have information in your path or the query part. Using REST you would normally put resource identifiers into the path and additional parameters into the query, e.g. like this (made up):

/questions/67156664/comments?count=5

This would mean:

  • comments for question with id 67156664 (path variable)
  • return up to 5 comments (query param)

Note again, that it often depends on your requirements, i.e. what part of your url you want to put the parameters in.

like image 124
Thomas Avatar answered Mar 14 '26 18:03

Thomas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!