@RequestParam Vs @PathVariable with Spring/SpringBoot

Introduction

In this chapter will see how to use @PathVariable, @RequestParam with Spring/SpringBoot and the difference between them .

1. @PathVariable

We use @PathVariable to get the value from the URI .

The implementation with Spring/SpringBoot

@GetMapping("/instruments/{symbol}")
public InstrumentBean getInstruementBySymbol(@PathVariable("symbol") String symbol) {
//call the service
}

By default the required property is true , if you want to make it optional you have to change ‘required=false‘.

@GetMapping("/{symbol}")
public InstrumentBean getInstruementBySymbol(@PathVariable(value = "symbol", required = false) String symbol) {
//call the service
}

The PathVariable “symbol” can be AMZN or APPL or any other Instrument Symbol.

Use case : http://@server/instruments/AMZN : Get Amazon informations

2. @RequestParam

We use @RequestParam to get a parameter from the query parameters.

The implementation with Spring/SpringBoot

@GetMapping(value = "/instruments")
public InstrumentBean getInstruementBySymbol(@RequestParam("symbol") String symbol) {
//call the service
}

By default the required property is true , if you want to make it optional you have to change ‘required=false‘.

@GetMapping(value = "/instruments")
public InstrumentBean getInstruementBySymbol(@RequestParam(value="symbol",required = false) String symbol) {
//call the service
}

The RequestParam “symbol” can be AMZN or APPL or any other Instrument Symbol.

Use case: http://@server/instruments?symbol=APPL : Get Apple informations.

3. Difference between @RequestParam and @PathVariable

Until now we see that RequestParam and PathVariable do the something but they have a little bit difference :

PathParams(for PathVariable) are location-dependent, while QueryParams(for RequestParam) are passed as a key value pair .

Suppose that the user doesn’t know the symbol of every instrument but he know the mnemonic (in market data mnemonic : the name of instrument like the label ) .

Use case: Delta Air Lines or S&P

@GetMapping("/instruments/{mnemonic}")
public InstrumentBean getInstrumentBy Mnemonic(@PathVariable("mnemonic") String symbol) {
//call the service
}@GetMapping(value = "/instruments")
public InstrumentBean getInstruementBy Mnemonic(@RequestParam("mnemonic") String symbol) {
//call the service
}

For @PathVariable extract the exactly value from URI :

http://@server/instruments/S&P

but RequestParam Get the encoded URI @Parameter:

http://@serveer/instruments?mnemonic=S&P

Summary

Both @PathVariable and @RequestParam are both used to extract values from the URL, by default they are required .

PathVariable get exact value but RequestParam extract the encoded value.

The main uses of @PathVariable or @RequestParam depend’s on the API designing .

Read more :