From the course: Java EE: RESTful Service with JAX-RS 2.0

@Consumes and @Produces

From the course: Java EE: RESTful Service with JAX-RS 2.0

Start my 1-month free trial

@Consumes and @Produces

- [Instructor] All resource methods can consume and produce content of almost any type. If you make a post request to a URI such as API slash books the rest API expects the HTTP body to contain a pay load that represents the resource it should create. This resource can be represented using any media type. Although typically it will be represented in either JSON or XML. Well it could be plain text, binary or a custom format. It doesn't matter, as long as there is a method in the resource class that can consume that media type. So the question is, how does the resource class know the methods media type and how does it select the right method to deal with it? Well, in the header of the HTTP request, there is a content type field that specifies the media type. And on the other end, the server end, the resource class has a method annotated with the matching type. So for example, if a request has a content type set to application JSON, the resource method that consumes this request is the method annotated with the same type. And likewise, if the content type were application XML, the method annotated media type application XML would handle that request. Just as a method can consume a payload of the given type it can produce a response payload of a specific type too. In the case of a post request the created resource can be returned back to the client. Conventionally, it is returned back in the same format as it was received. So returns back as JSON if it was posted in JSON. Nevertheless, this does not have to be the case. There is another HTTP header that specifies the accepted return media type and there is a matching annotation on the resource methods also. Such a method will be annotated with the produces annotation and passes the media type application JSON. So if a full example would be an HTTP post request with a content type of JSON and an accept type of JSON. And the corresponding resource method would be annotated appropriately with both the consumes and the produces annotation with immediate type application JSON. Okay so let's jump to the code and add these media type annotations.

Contents