Choosing a Rails XML serializer for your API
Published on 2021-05-18
It’s 2021 and you need to build an XML API. Yes, JSON would be preferred by most developers, but sometimes you need to offer both. What are your options?
In contrast to the JSON serializers for Ruby on Rails, it seems that not many XML serializers are available. The few that I found are all quite old, but seem still maintained and are good options to use. Only ActiveModel::Serializers::Xml seems to have become unmaintained, with it’s last release in 2017.
Builder is probably one of the best known XML generators. The original author doesn’t maintain it anymore, but an active fork has appeared. The Builder Ruby on Rails view integration is nice, where you can just create a
.xml.builder file and start developing your XML outputn in their simple DSL. This simple setup is very useful when combined with caching, the output of Builder can easly be cached.
Nokogiri is a default dependency of Rails or some of its gems. It was one of the gems that significantly slowed down
bundle install because it comes bundled with its own versions of libxml and some other C libraries. They recently fixed the slow install by offering binaries for various operating systems.
The authors try to maintain Nokogiri as best as they can, which includes updates to the bundled C libraries when they contain security issues. Last release is therefor only a few days ago as of this writing.
Nokogiri doesn’t have actual Rails view integrations like Builder, so generating XML is done by hand. The output can then be passed to render from your controller action. I couldn’t find actual benchmarks, but various people on the internet believe Nokogiri is one of the slowest options you can choose.
I just discovered OX. Seems quite actively maintained and their last release is only a few weeks old. It seems to be the fastest Ruby XML serializers available, with only dependencies on basic, default C libraries an no issues with libxml as Nokogiri has.
Generating XML is done in a similar way as Nokogiri and ActiveModel::Serializers::Xml, using plain Ruby objects.
Gyoku generates XML from ruby hashes. This can be quite handy, but with more complex, conditional XML output I believe this might become quite cumbersome. Last release was only a few months ago.
When ease of use is of the most concern I would probably advise you to use Builder. If speed becomes an issue you should probably pick OX.