srividya
srividya

Reputation: 81

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.

Upvotes: 5

Views: 17857

Answers (3)

EricSchaefer
EricSchaefer

Reputation: 26340

@PathVariable is for parts of the path (i.e. /person/{id})

@RequestParam is for the GET query parameters (i.e. /person?name="Bob").

@RequestBody is for the actual body of a request.

Upvotes: 13

Ganesh Jadhav
Ganesh Jadhav

Reputation: 802

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

Upvotes: 19

Jeelan
Jeelan

Reputation: 71

@RequestBody used with POST Verb whereas @RequestParam and @pathVariable used with GET Verb

@RequstParam : It extract the value from query string used for fitering,sorting and pagination In Request Param the values can be encrypted localhost:8080/getBooks?start=1&end=100

@pathVariable : It extract value from URI Path In Path variable the value cannot be encoded Its used get the data based on the value

Reference: https://www.baeldung.com/spring-requestparam-vs-pathvariable

Upvotes: 1

Related Questions