0

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
1

2 Answers 2

5

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

    }`
Sign up to request clarification or add additional context in comments.

Comments

1

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"));

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.