JeanValjean
JeanValjean

Reputation: 17713

Spring Mvc and MediaType for consumes in @RequestMapping for a get rest request

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?

Upvotes: 5

Views: 13579

Answers (4)

Behrang Saeedzadeh
Behrang Saeedzadeh

Reputation: 47913

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,
}, ...)

Upvotes: 0

ParagFlume
ParagFlume

Reputation: 979

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

Upvotes: 0

mtyurt
mtyurt

Reputation: 3449

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.

Upvotes: 0

jny
jny

Reputation: 8057

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.

Upvotes: 2

Related Questions