Choosing a Rails XML serializer for your API in 2021

Published on 18-05-2021

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

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

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.

OX

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

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.

Conclusion

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.

Let me know on Twitter if you think I left out an important option!

Want to test Callcounter?

You can start gathering data in minutes

Start 7 day trial

No credit card required