when should I use PathVariable and when should I use RequestParam

Viewed 119

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?

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.

Related