Reputation: 1125
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?
Upvotes: 2
Views: 10672
Reputation: 815
Although it has been more than 4 years already since this question was asked, putting an answer for people in same sort of problem in the future.
Since the Request Method
is POST
in both cases, @PostMapping
can be used replacing @RequestMapping
.
With @PostMapping
it is possible to have multiple MediaTypes. For instance, below code should not cause any problems.
@PostMapping(value = "/configuration", consumes = { MediaType.APPLICATION_JSON_VALUE, MediaType.MULTIPART_FORM_DATA_VALUE })
public String setConfiguration(@RequestPart MultipartFile file, @RequestBody Configuration configuration)
NOTE: As the method parameters are different, @Mhowell's approach seems right.
Upvotes: 3
Reputation: 139
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.
Upvotes: 3