Skip to main content

Mike Kreuzer

A Ruby interface for the Mastodon API

February 17, 2023

Ruby's library for dealing with Mastodon's API's been left languishing for years. The last release was in January 2019. There are plenty of libraries for dealing with the API written in other languages, complete with web pages & example code. But the language Mastodon's written in? Not so much.

What's especially annoying about this is people have submitted code, but it's been left to sit there, unreviewed. We can still benefit from those other people's hard work though.

I forked one of the forks & merged another fork's code into it to get the two missing features I especially needed, namely the ability to run on a version of Ruby newer than 2.6, and the ability to deal with paginated results.

Update November 2023: I've taken my code off Github, this code's no longer available there.

You can require that version:

You used to be able to require that version…. maybe one day soon…

gemfile do
  source 'https://rubygems.org'
  gem 'http', '~> 4.0'
  gem 'mastodon-api', git: 'git@github.com:mikekreuzer/mastodon-api.git', branch: 'merged-forks'
end
require 'mastodon'

Then after setting up a client in the way suggested in the original README, get paginated results by looping over the API's responses, something like for example:

next_max = nil
results = []
loop do
  data = client.followers(ID, { limit: 80, max_id: next_max })
  next_max = data.next_max_id
  results += data.to_a

  break if next_max.nil?
end

That code could be abstracted out into a method where you only had to request a number of replies or even no particular number expecting to get all of them, and if there was paging to be done it'd happen under the hood. Pretty easily too.

But that's left as an exercise for the reader, for the same reason I haven't merged the feature branch into main on that forked repo, or renamed the gem & pushed it to RubyGems as a standalone thing. That way lies madness. Or at least open source obligations I'd also be glacially slow to meet.

Tags: