# Spring API input parameters

In 
API
Published 2022-12-03

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

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();
    }

}

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;
    }
    
}