Difference Between @PathVariable & @RequestParam

Whenever we start working on API design we always have few things in mind , What I have to take as PathVariable and which as RequestParam.

Difference Between @PathVariable & RequestParam

Most of the people/developers don’t even know what exactly @PathVariable is and what @RequestParam, and Importantly when to use them, In this Article, we will talk about What is PathVariable & RequestParam and when to use which.

What is @PathVariable?

@PathVariable is an Annotation used while creating APIs , It is a URI Placeholder which goes in URI of the API and this template will be replaced with the actual value of it.
Example – /customer/{customerId}/address

@GetMapping("/customer/{customerId}/address")
public ResponseEntity<Address> getCustomerAddress(@PathVariable("customerId") Long id )
{
          // your code goes here

}

Here {customerId} is treated as PathVariable in controller

When to use @PathVariable?

The Most Important point to understand is when to use @PathVariable?

  • @PathVariable is used when we have to implicate mandatory parameter and we want to pass as a URI only
  • When we want the API to be self-explanatory for the external interface to understand it 
    Ex – /customer/1/address = this is showing that this API will return the address of the customer having id 1

Also learn: CRUD Operation in Spring boot

What is @RequestParam?

@RequestParam is used to handle one or more dynamic value passed by API and which need to be required by the controller method to do specific tasks.

We can consider @RequestParam as a query param we passed in Servelet .

Example – “/customer?customerId=1

here customerId=1 is the requestParam we are passing in API

If we want to send more than one request param we will send it like below 

/customer?customerId=1&addressId=23

When to use RequestParam?

@RequestParam is used when we want a parameter to be optional. we can also make the parameter as mandatory but by default, the parameter is considered as Mandatory.

@GetMapping("/customer")
public ResponseEntity<Customer> getCustomer(@RequestParam("customerId") Long id ){
      // your code goes here 
}

With Optional Request Param, it will be 

@GetMapping("/customer")
public ResponseEntity<Customer> getCustomer(@RequestParam(value="customerId" , required=false) Long id ){
      // your code goes here 
}

 

I hope this will be helpful for you guys, If you have any issue do let us know or leave us a comment below.

 

Thanks 

 

 

 

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *