Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between @PathVariable, @RequestParam, and @RequestBody

I understand what the @PathVariable, @RequestParam and @RequestBody does in Spring, but not clear on which scenarios we have to use them as they are used for extracting value from the URI. Why we have to send data like localhost:8080/getBooks/time and localhost:8080/getBooks?book=time.

like image 610
srividya Avatar asked Aug 23 '26 15:08

srividya


1 Answers

Example 1:
@RequestParam is used mainly for filtering purposes Lets say you want to get George Martin's book:
GET localhost:8080/books?author=georgemartin
Here we pass author=georgemartin as request parameter. This will supposedly get all of Martin's books, example game of thrones series. This will be used mainly for GET operation.

Example 2:
@PathVariable is used mainly for getting individual objects or piece of data Lets say you want to get a book by its id:
GET localhost:8080/books/1
Here we pass 1 as path variable. This will supposedly get the 1 book with id 1, example first part of game of thrones' book. This will be used mainly for DELETE/GET operation.

Example 3:
@RequestBody is used mainly for saving object(s)(or piece of data) Lets say you want to add a book:
POST localhost:8080/books/ With request body having following attributes:

{
  "author":"George Martin",
  "Book":"Game of thrones"
  ...
  ...
}

This will add a book to the db. This would be used mainly for PUT/POST operation.


Note: never use verb naming for endpoint, instead, use plural nouns. So books/ is ideal instead of getbooks/.
Reference/Read more:
https://stackoverflow.blog/2020/03/02/best-practices-for-rest-api-design/#h-use-nouns-instead-of-verbs-in-endpoint-paths
https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/bind/annotation/RequestBody.html
https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/bind/annotation/RequestParam.html
https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/bind/annotation/PathVariable.html
like image 127
Ganesh Jadhav Avatar answered Aug 25 '26 04:08

Ganesh Jadhav