I'm implementing a REST application using Spring Boot.
I want to specify the consumes
parameter for the @RequestMapping
annotation.
The rest call should be something like:
http: // mysite.com/resource/123
In the controller I handle this as follows:
@RequestMapping(value = "/resource/{id}", method = RequestMethod.GET,
consumes = XXX, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public Scenario getResource(@PathVariable("id") final long id) {
//...
}
The default value, i.e. all, is obvious and not specific. So, which should be the correct MediaType
for consumes
?
According to the documentation, consumes
has to match the value of Content-Type
header so the value you need to send for the mapping depends on what the client sets in the header.
With just a path variable, you do not need any content type. If you leave it blank, Spring will map all /resource/{id}
requests to this handler regardless of the content type header. If you want to specify a content type, choose a default one like text/plain
. But be aware that you have to change the request to have the same content-type header.
To consume data from url path or url query param, you don't need to explicitly specify any media format. It works with the default format.
@RequestMapping(value={"/resource/{id}"}, method={RequestMethod.GET})
public String getResource1(@PathVariable("id") Long id){
// other code here
return "";
}
@RequestMapping(value={"/resource/{id}"}, method={RequestMethod.POST})
public String getResource2(@PathVariable("id") Long id, @ModelAttribute Person person){
// other code here
return "";
}
It depends on your requirements. If you only want to allow consumption of JSON
, for example, then:
@RequestMapping(consumes = MediaType.APPLICATION_JSON_VALUE, ...)
If you want to consume multiple media types, then you can specify them in an array:
@RequestMapping(consumes = {
MediaType.APPLICATION_JSON_VALUE,
MediaType.APPLICATION_XML_VALUE,
}, ...)