#
Spring API input parameters
This tutorial explains to you the input parameter types we can use in a Spring API.
In a Spring API, the request is received by the Controller. It can handle 3 input parameter types:
- PathVariable : extracts a value from URL, but before "?" sign
- RequestParam : extracts a value from URL, but after "?" sign
- RequestBody : maps the content of the body request to a variable
If we have an HTTP incoming request http://domain.com:8080/employee/10?name=John
we can have:
- @PathVariable : to extract the department number (i.e. "10") from the URL
- @RequestParam annotation to retrieve the query parameter
name
Info
URL parameters or query strings are the part of a URL that typically comes after a question mark (?) and are used to pass data along with the URL.
In order to test how all those work, you can add a Controller class to a Spring Boot Application.
You can use the following EmployeeController
for testing:
package com.example.restdemo.employee;
import org.springframework.web.bind.annotation.*;
@RestController
public class EmployeeController {
@GetMapping("/employee/{deptNumber}")
String getDeptNo(@PathVariable String deptNumber) {
return deptNumber;
}
@GetMapping("/employee")
String getEmpId(@RequestParam String id, @RequestParam(required = false) String name) {
return id+"/"+name;
}
@PostMapping(value="/employee", consumes = "application/json")
String getEmployees(@RequestBody Employee newEmployee) {
return newEmployee.getId();
}
}
Info
In the POST method, you can see how the JSON request body is converted into an Employee object.
The JSON request body could be like this:
{"id": "200",
"name": "Brown",
"department":"20",
"age":30}
For having the example working we need to have the Employee
class created as well:
package com.example.restdemo.employee;
public class Employee {
private String id;
private String name;
private String department;
private int age;
public Employee(String id, String name, String department, int age) {
this.id = id;
this.name = name;
this.department = department;
this.age = age;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}