Reputation: 88
I am very new to Spring Boot and trying out different things.
I have a class in which a method does simple calculation, accepts two numbers and give addition.Now i want to pass the numbers through api in json format and return the addition of the number.
Can we pass the variables in a @POSTMapping
and return the result ?
Controller class
@RestController
@RequestMapping(value="/TC")
public class CountSpringAppController {
@Autowired
private CountService countService;
@PostMapping(value="/add/{number1}/{number2}")
public int getCount(@PathVariable int num1,@PathVariable int num2) {
return countService.count(num1, num2);
}`
service class
@Service
public class CountService {
public int count(int num1, int num2) {
return num1+num2;
}
}
input
{
"num1":1,
"num2":1
}
output
2
Upvotes: 0
Views: 6100
Reputation: 616
Make a Num class which will accept json
Class Num{
int num1;
int num2;
//getter setter
}
now use that class for getting data from json body
@RequestMapping(value="/add",method = RequestMethod.POST, consumes="application/json", produces = "application/json")
public int getCount(@RequestBody Num request) {
return countService.count(request.getNum1(),request.getNum2());
}`
Upvotes: 5
Reputation: 23246
You can do as below. This prevents the need for an additional data class:
@PostMapping(value="/add")
public int getCount(@RequestBody Map<String, Integer> data) {
return countService.count(data.get("number1"), data.get("number2"));
}
Upvotes: 1