Handling YAML format in your REST with Spring Boot

In general a REST service serves JSON document formats. In Spring Boot it is even the standard without having to configure anything.
Over HTTP we have the ability to send a Content-Type as header to instruct the server to return a certain document format (Mime type).
Besides handling JSON, XML is another common document format. But what if we want to serve or read a YAML document format?

This tutorial provides the required steps to be able to handle objects in YAML format. To be able to send a YAML Content-Type with the header, and to be able to serialize and deserialize with the existing ObjectMappers of Jackson. This tutorial will use Spring Boot, Jackson and a YAML dataformat extension library for Jackson.

Add dependency

First we need to add the YAML Jackson extension to our Gradle build file.

Register ObjectMapper

Now we can create a specific ObjectMapper with a registered YAMLFactory.
To create our YAML ObjectMapper the following line will:

Now we have registered two ObjectMapper instances. One for JSON and one for YAML. Both with the option to enable or disable features in the ObjectMapper.

Register MessageConverter and Content Negotiation

Read YAML file

Another option we have is to read YAML files and transform them into Objects. Lets say we already have a FileService that has functionality to read a file as an InputStream.

To transform this InputStream into an Object, we autowire the YAML ObjectMapper and provide the returned InputStream to the ObjectMapper.

NB. For this example Lombok was used (http://projectlombok.org)

Leave a Reply

Your email address will not be published. Required fields are marked *