View video tutorial

SPRING BOOT @PathVariable

SPRING BOOT

The @PathVariable annotation is used to extract dynamic values ​​from the URI path of a request and bind them to method parameters in a REST controller.

Spring Boot @PathVariable Annotation


➔ The @PathVariable annotation helps extract values ​​from URL paths using URI template variables and bind them to method parameters of a REST controller.

➔ The @PathVariable annotation is used to extract dynamic values ​​from the URI path of an HTTP request to the server and bind those values ​​to a part of the URL in a method parameter of the controller, which is defined as a URI template variable within curly brackets {}.

Key characteristics of the @PathVariable annotation:


➔ Mainly used in RESTful APIs to identify a specific resource, such as /student/{id}, where {id} is a variable.

➔ @PathVariable dynamically maps the method parameter to a URI template variable enclosed in curly brackets {}.

➔ A single handler method can handle multiple path variables, such as customers/{customerid}/orders/{orderid}.

Syntax
URL:  https://localhost:8090/customers/100/orders/500

Template variable: @GetMapping("customers/{customerid}/orders/{orderid}")

Method parameters:  handlerMethod(@PathVariable("customerid") int cid, @PathVariable("orderid") int oid)

➔ Spring Boot automatically converts string template variables to the declared parameter type.

➔ If the name of the method parameter and the name of the URI template variable are different, the name must be explicitly declared in the annotation, for example: handlerMethod(@Pathvariable("customerid") int cid, @Pathvariable("orderid") int oid)

➔ If the name of the method parameter and the name of the URI template variable are the same, it is optional to declare the explicit name in the annotation, such as handlerMethod(@Pathvariable int customerid, @Pathvariable int orderid)

Making Path Variables Optional in URL:


➔ The path variable is required by default and can be made optional by setting required=false and mapping the URI to handle both present and absent states.

For example
URL: http://localhost:8090/customers/100
URL: http://localhost:8090/customers
URI Mapping: @GetMapping({"/customer", "/customer/{customerid}"})
Method Parameter: handlerMethod(@Pathvariable(name="customerid" required = false) int cid)

Setting a default value for a path variable


➔ The @PathVariable annotation has no built-in defaultValue attribute, so a default value cannot be set using an attribute like @RequestParam.

➔ Path variables are part of the URL structure and if a variable is missing, technically the URL itself is changed. Therefore, if the path variable is missing, it fails to match the specified route.

➔ However, the default value for the PathVariable can be set using the following techniques:

Method 1. Multiple path mapping

➔ The ideal way to provide a default value for a path variable is to define two paths, one of which includes the variable and the other does not.

@GetMapping({"/api/customer", "/api/customer/{id}"})
public String getCustomer(@PathVariable(name="id" required = false) String cid) {
    if (cid == null) {
        cid = "assign_default_value"; // Assign default value.
    }
    return  cid;
}

➔ Here, if required=false is set, spring boot will not throw any exception if the {id} segment is missing.

Method 2. Wrap the method parameter in Optional type.
@GetMapping({"/api/customer", "/api/customer/{id}"})
public String getCustomer(@PathVariable Optional<String> id) {
    return "Hello, " + name.orElse("default_value"); // set the default value
}

Method 3. Using separate handler methods:

➔ The ideal way to provide a default value for a path variable is to define two paths, one of which includes the variable and the other does not.

@GetMapping("/api/customer")
public String getCustomer() {
    return processData("default_id");  //default_value
}
@GetMapping("/api/customer/{id}")
public String getCustomer(@PathVariable String id) {
    return processData(id);
}
private String processCustomer(String val) {
    return  val;
}

Now practice this chapter in your learning environment.

02 Create a Controller class

Create controller

Name it anything, for example UsersController.

Create UsersController

Controller Code
package com.exam.helloworld;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UsersController {
	@GetMapping("/api/customers/{id}")
	public String customerHandler( @PathVariable("id") Long id) {
		return "\nPathVariable is: " + id;
	}
}

03 Run HelloworldApplication.java

spring boot application run

After successfully run the application.

restapi server run

Now test the @PathVariable request url in Postman (an API testing tool).

Send Text data.

PutMapping  text

Example multiple @PathVariable
package com.exam.helloworld;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UsersController {
	@GetMapping("/api/customers/{id}/orders/{orderid}")
	public String customerHandler( @PathVariable("id") Long id, @PathVariable("orderid") Long oid) {
		return "Customer ID: " + id +"\nOrder ID: " + oid;
	}
}


Multiple @PathVariable, output
RequestParam PutMapping output

Make @PathVariable URL value optional
Example @PathVariable
package com.exam.helloworld;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UsersController {
	@GetMapping({"/api/customers", "/api/customers/{id}"})
	public String customerHandler( @PathVariable(name = "id", required = false) Long cid) {
		if(cid==null) {
			cid=(long)500;
		}
		return "Customer ID: " + cid ;
	}
}


@PathVariable URL value optional, output
RequestParam PutMapping output