Monday, January 23, 2017

Fixing "415: Unsupported Media Type" error on spring REST service

This error returned from container when the request content is not in expected format of the service. This could mean that the request doesn't have the "content-type" http header with appropriate value or the service is configured to process a different request content-type.


But, If we have configured everything correct,

1. Request mapping(@RequestMapping),
2. Request body(@RequestBody), Response body(@ResponseBody) annotations
3. and we see in our container startup logs that the URL is mapped
4. If we are sending JSON or XML request body or returning JSON or XML response body and have the appropriate http headers in request (content-type: application/json) and response(Accept: application/json)
5. We have the jackson libraries in application runtime classpath

But, still see this http error while invoking the service?

Don't worry! The issue is small, just make sure you have not missed any of the following configuration in your spring application configuration. Particularly, the mvc:annotation-driven or @EnableWebMvc is needed in order interpret your @RequestBody and @ResponseBody annotations correctly.

XML Configuration
<context:annotation-config />
<context:component-scan base-package="com.example.app"/>
<mvc:annotation-driven></mvc:annotation-driven>

Java Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.example.app")

Sometimes, missing this configuration or placing these configurations at different places might also result in http 404-resource not found error.

Note: This is observed with spring framework 4.3.5