I'm developing a REST API with Spring, and would like an API to handle POST requests with different media types, namely JSON form data in request body, or a JSON file sent through the request.
So when I have two separate methods with such signatures both work fine,
@RequestMapping(value = "/configuration" , method = RequestMethod.POST, consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
public String setConfiguration(@RequestPart MultipartFile file)
@RequestMapping(value = "/configuration" , method = RequestMethod.POST, consumes = {MediaType.APPLICATION_JSON_VALUE}
public String setConfiguration(@RequestBody Configuration configuration)
The handling logic of both methods are almost the same, so I'm trying to use one method to absorb both kinds of data format with this code:
@RequestMapping(value = "/configuration" , method = RequestMethod.POST, consumes = {MediaType.APPLICATION_JSON_VALUE, MediaType.MULTIPART_FORM_DATA_VALUE})
public String setConfiguration(@RequestPart MultipartFile file, @RequestBody Configuration configuration)
However an error response will be returned as,
{"timestamp": 1443744180124,
"status": 500,
"error": "Internal Server Error",
"exception": "org.springframework.web.multipart.MultipartException",
"message": "The current request is not a multipart request",
"path": "/v1/testconfiguration"
}
Wondering if I have some fundamental misunderstanding of media type of REST and if this is doable how can I achieve it with Spring?
If they both work as separate methods then you are better off just doing it that way.
It is probably be neater and easier to read, there's no need to try and make optimisations like you are doing at the moment, not that I don't labour over my own code.