Tutorial · Ruby

Instagram and TikTok API in Ruby

A standard-library Ruby client: Net::HTTP, JSON and an Enumerator for cursor paging, so .first(100) or .take_while stops calling when you have enough.

Short answer. Net::HTTP::Get with the X-Api-Key header, JSON.parse the body and follow pagination.next_cursor. The module below wraps that with retries and a lazy paginate; drop it into a Rails app or a script.

Facts checked 2 December 2026. Prices change: follow the links before you decide.

Set up

  • Ruby 3 or newer; no gems. Set HANDLEHAUL_API_KEY in the environment or Rails credentials and pass it as api_key:.
  • For Rails background jobs, build one client per job run; the client only keeps a credit counter.

The client module

get retries 429 after Retry-After and 502/503/504 with a growing wait (free answers), and raises HandleHaul::Error with status and code otherwise.

paginate yields rows page by page; without a block it returns an Enumerator, so .first(5) stops after the page that holds the fifth row. Each page is one call.

handlehaul.rbRun: ruby handlehaul.rb

# A small HandleHaul API client for Ruby 3 (standard library only): retries, cursor paging and clear errors.
#   export HANDLEHAUL_API_KEY=kd_live_...   # or a free kd_test_ key for sample data
#   ruby handlehaul.rb
require "json"
require "net/http"
require "uri"

module HandleHaul
  API = "https://api.handlehaul.com/v1"
  RETRY = %w[429 502 503 504].freeze # never charged; other 4xx answers will not change on a retry

  class Error < StandardError
    attr_reader :status, :code

    def initialize(status, code, message)
      @status = status
      @code = code
      super("#{status} #{code}: #{message}")
    end
  end

  class Client
    attr_reader :credits # what this client spent, from meta.credits_charged

    def initialize(api_key: ENV.fetch("HANDLEHAUL_API_KEY"), max_tries: 5)
      @api_key = api_key
      @max_tries = max_tries
      @credits = 0
    end

    # One call. Retries 429 (after Retry-After) and 502/503/504 (growing wait).
    def get(path, params = {})
      uri = URI(API + path)
      uri.query = URI.encode_www_form(params) unless params.empty?
      @max_tries.times do |attempt|
        req = Net::HTTP::Get.new(uri)
        req["X-Api-Key"] = @api_key
        res = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https", read_timeout: 60) { |h| h.request(req) }
        if RETRY.include?(res.code) && attempt < @max_tries - 1
          sleep((res["Retry-After"] || (2**attempt) + rand).to_f)
          next
        end
        body = JSON.parse(res.body)
        raise Error.new(res.code.to_i, body.dig("error", "code"), body.dig("error", "message")) unless res.is_a?(Net::HTTPSuccess)

        @credits += body.dig("meta", "credits_charged").to_i
        return body
      end
      raise Error.new(429, "rate_limited", "still limited after retries")
    end

    # Every row of a list endpoint, one page (one call) at a time. Stop the loop to stop paying.
    def paginate(path, params = {}, max_pages: 10)
      return enum_for(:paginate, path, params, max_pages: max_pages) unless block_given?

      params = params.dup
      max_pages.times do
        body = get(path, params)
        body["data"].each { |row| yield row }
        break unless body["pagination"]["has_more"]

        params["cursor"] = body["pagination"]["next_cursor"]
      end
    end
  end
end

if __FILE__ == $PROGRAM_NAME
  hh = HandleHaul::Client.new
  tag = hh.get("/tiktok/hashtags/booktok")["data"]
  puts "##{tag["name"]}: #{tag["post_count"]} posts, #{tag["view_count"]} views"
  hh.paginate("/tiktok/hashtags/booktok/posts", max_pages: 2).first(5).each do |post|
    puts [post["created_at"], post.dig("counts", "views"), post["url"]].join(" ")
  end
  begin
    hh.get("/instagram/users/private_demo/followers")
  rescue HandleHaul::Error => e
    puts "expected error: #{e.code}"
  end
  puts "credits used: #{hh.credits}"
end
Tested 2026-12-02 against a local mock serving the documented API responses (retry on 429, cursor paging, a private-account error).

Every endpoint in Ruby

Each page below has a complete Ruby program for one route, the parameters, a sample response and what it costs. The link opens the Ruby tab.

Instagram

Instagram endpoint tutorials
TutorialRoute
ProfileGET /v1/instagram/users/{user}
Account detailsGET /v1/instagram/users/{user}/account-details
Similar accountsGET /v1/instagram/users/{user}/related
FollowersGET /v1/instagram/users/{user}/followers
FollowingGET /v1/instagram/users/{user}/following
PostsGET /v1/instagram/users/{user}/posts
ReelsGET /v1/instagram/users/{user}/reels
Tagged postsGET /v1/instagram/users/{user}/tagged
RepostsGET /v1/instagram/users/{user}/reposts
Post or reelGET /v1/instagram/posts/{post}
Post stats (batch)GET /v1/instagram/posts/stats
CommentsGET /v1/instagram/posts/{post}/comments
Comment repliesGET /v1/instagram/comments/{comment}/replies
Post likersGET /v1/instagram/posts/{post}/likers
Comment likersGET /v1/instagram/comments/{comment}/likers
StoriesGET /v1/instagram/users/{user}/stories
Story by idGET /v1/instagram/stories/{story}
HighlightsGET /v1/instagram/users/{user}/highlights
Highlight storiesGET /v1/instagram/highlights/{highlight}
Search hashtagsGET /v1/instagram/search/hashtags
HashtagGET /v1/instagram/hashtags/{tag}
Hashtag postsGET /v1/instagram/hashtags/{tag}/posts
Search placesGET /v1/instagram/search/places
PlaceGET /v1/instagram/places/{place}
Place postsGET /v1/instagram/places/{place}/posts
Search audioGET /v1/instagram/search/audio
Trending audioGET /v1/instagram/audio/trending
AudioGET /v1/instagram/audio/{audio}
Reels using audioGET /v1/instagram/audio/{audio}/reels
Search accountsGET /v1/instagram/search/users
URL resolverGET /v1/instagram/resolve

TikTok

TikTok endpoint tutorials
TutorialRoute
ProfileGET /v1/tiktok/users/{user}
Suggested accountsGET /v1/tiktok/users/{user}/suggested
FollowersGET /v1/tiktok/users/{user}/followers
FollowingGET /v1/tiktok/users/{user}/following
PostsGET /v1/tiktok/users/{user}/posts
RepostsGET /v1/tiktok/users/{user}/reposts
Liked videosGET /v1/tiktok/users/{user}/liked
PlaylistsGET /v1/tiktok/users/{user}/playlists
StoriesGET /v1/tiktok/users/{user}/stories
Video or photo postGET /v1/tiktok/posts/{post}
CommentsGET /v1/tiktok/posts/{post}/comments
Comment repliesGET /v1/tiktok/comments/{comment}/replies
TranscriptGET /v1/tiktok/posts/{post}/transcript
SoundGET /v1/tiktok/music/{music}
Posts using a soundGET /v1/tiktok/music/{music}/posts
HashtagGET /v1/tiktok/hashtags/{tag}
Hashtag postsGET /v1/tiktok/hashtags/{tag}/posts
SearchGET /v1/tiktok/search

Ruby: questions

Is there a Ruby gem for HandleHaul?
Not yet: the official SDKs are Node.js and Python. The module above uses only the standard library and covers every route, since they all share one JSON shape.
Faraday or Net::HTTP?
Either. Faraday with a retry middleware works if your app already uses it: retry 429, 502, 503 and 504, honour Retry-After, and never retry 400, 401, 402, 403 or 404.
How do I export rows to CSV in Ruby?
require "csv", open a file, and write csv << row.values_at("username", "full_name") inside the paginate block. Rows reach the file as pages arrive, so an interrupted run keeps what it fetched.

Build it in Ruby

One key for Instagram and TikTok. $1.40 to $0.80 per 1,000 calls; failed calls and cache hits are free.

Want to test first? Sandbox keys are free and unlimited, with sample data in the live schema.