Search code examples
springspring-mvcspring-boothttp-postspring-restcontroller

Spring Boot - How can I pass custom values in HTTP Post api?


I'm new with Spring Boot and I have difficult to understand how can I pass data. For example:

I want pass those data to my server:

{
    "code", 1,
    "name": "C01"
}

So I have create always a custom Object with code and name as attributes to have this http post api?

@RequestMapping(value = "/new/", method = RequestMethod.POST)
public ResponseEntity<?> createOrder(@RequestBody CustomObject customObject){
    ...
}

Another solution I see that can be this but I can't pass numbers (int code), right?

@RequestMapping(value = "/new/{code}/{name}", method = RequestMethod.POST)
    public ResponseEntity<?> createOrder(@PathVariable("code") int code, @PathVariable("name") String name) {
        ...
}

Kind regards :)


Solution

  • You can pass code and name as PathVariables just like in your example:

    @RequestMapping(value = "/new/{code}/{name}")
    public ResponseEntity<?> createOrder(@PathVariable("code") int code, @PathVariable("name") String name) {
        ...
    }
    

    A PathVariable can be an int or a String or a long or a Date, according to the docs:

    A @PathVariable argument can be of any simple type such as int, long, Date, etc. Spring automatically converts to the appropriate type or throws a TypeMismatchException if it fails to do so.

    You could also define a PathVariable of type Map<String, Object> like this:

    @RequestMapping(value = "/new/{code}/{name}")
    public ResponseEntity<?> createOrder(@PathVariable("map") Map<String, Object> map) {
        Integer code = (Integer) map.get("code");
        String name = (String) map.get("name");
        ...
    }
    

    You could even use @RequestParam and supply the data in the form of URL query parameters.

    So, there are numerous ways in which data can be passed to a Spring MVC controller (more details in the docs) but I think the convention for posting complex data (by "complex" I mean more than a single piece of state) is to define a request body which contains a serialised form of that complex state i.e. what you showed in the first example in your queston:

    @RequestMapping(value = "/new/", method = RequestMethod.POST)
    public ResponseEntity<?> createOrder(@RequestBody CustomObject customObject){
        ...
    }