News Ticker

JAX-RS Media Types

Java EE: Working with JAX-RS @Consumes and @Produces Java EE: Working with JAX-RS @Consumes and @Produces

Introduction to @Consumes and @Produces

All resource methods can consume and produce content of almost any type. If you make a POST request to a URI, such as api/books, the REST API expects the HTTP body to contain a payload 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, but 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.

C:\Alex\study books and notes\Images\JAX-RS course\JAX-RS_2.0_Working_with_@Consumes_and_@Produces_annotations.png
Learn to work with @Consumes and @Produces annotations

Resource Method Selection

So, the question is: how does the resource class know the payload’s 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 the 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 with MediaType APPLICATION_XML would handle that request.

Consume and Produce JSON

Just as a method can consume a payload of a given type, it can produce a response payload of a specific media 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 format, 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 method also. Such a method would be annotated with the @Produces annotation and passed the MediaType APPLICATION_JSON.

So 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 a @Consumes and @Produces annotation with the MediaType APPLICATION_JSON.

Learn More

If you would like to learn to work with @Consumes and @Produces why not have a look at my online video course about JAX-RS. In this course, you will learn all about working with JAX-RS while building a RESTful APIs for an online bookshop.

Leave a Reply

%d bloggers like this: