Post to social media from Ruby with Ampost

By Published Updated

The Ampost Ruby SDK publishes a post to every network you name with one call, so a Ruby script or a Rails app needs no per-network OAuth. Install the ampost gem, download the script below, set AMPOST_API_KEY, and run it with your text and networks.

What you'll build

  • A command-line script that publishes a text, link, image or video post to several social networks at once, now or at a scheduled time.
  • The same call in your own code: a Rails app, an Active Job or Sidekiq worker, a rake task or an AI agent.

Before you start

  • An Ampost account. The Free plan includes the REST API (2 social accounts and 15 posts every 30 days); scheduling needs the Pro plan or higher, and X the Max and Scale plans. See pricing.
  • An API key from Setup → API keys. The key is shown once, so copy it when you create it. Treat it like a password.
  • At least one connected social account, under Setup → Connections in the dashboard.
  • Ruby 3.1 or later. The gem has no runtime dependencies: it uses net/http and json from the standard library.

Download

Free to use and change. The file is shown in full below, so you can read it before you run it.

post_with_sdk.rb
#!/usr/bin/env ruby
# frozen_string_literal: true

# Post to social media with the Ampost Ruby SDK.
#
# One call publishes (or schedules) a post on every network you name:
# Instagram, Facebook, Threads, X, YouTube, Pinterest, Bluesky, Telegram and
# Discord. Ruby 3.1+ and the `ampost` gem:
#
#   gem install ampost
#
#   export AMPOST_API_KEY=amp_live_...
#   ruby post_with_sdk.rb --text "Hello from Ruby" --platforms bluesky,threads
#   ruby post_with_sdk.rb --text "New post" --platforms threads --link https://example.com/post
#   ruby post_with_sdk.rb --text "Launch" --platforms instagram,threads --media launch.jpg
#   ruby post_with_sdk.rb --text "Tomorrow" --platforms bluesky --schedule 2027-01-14T15:00:00Z
#
# Guide: https://ampost.io/how-to/post-to-social-media-from-ruby
# SDK: https://ampost.io/docs/tools/ruby-sdk

require "optparse"
require "ampost"

def parse_options(argv)
  options = { media_type: "image" }
  parser = OptionParser.new do |opts|
    opts.banner = "Usage: ruby post_with_sdk.rb --text TEXT --platforms LIST [options]"
    opts.on("--text TEXT", "the post text") { |v| options[:text] = v }
    opts.on("--platforms LIST",
            "comma-separated: instagram, facebook, threads, twitter, youtube, pinterest, bluesky, telegram, discord") do |v|
      options[:platforms] = v
    end
    opts.on("--link URL", "a link to attach (linkUrl)") { |v| options[:link] = v }
    opts.on("--media FILE_OR_URL", "an image or video: a local file or a public https URL") { |v| options[:media] = v }
    opts.on("--media-type TYPE", %w[image video], "the type of a --media URL: image (default) or video") do |v|
      options[:media_type] = v
    end
    opts.on("--schedule TIME", "publish later, at this ISO 8601 time, e.g. 2027-01-14T15:00:00Z") { |v| options[:schedule] = v }
    opts.on("--idempotency-key KEY", "reuse a key to make re-runs safe (default: one per run)") do |v|
      options[:idempotency_key] = v
    end
  end
  parser.parse!(argv)
  abort(parser.help) unless options[:text] && options[:platforms]
  options
end

def build_body(client, options)
  platforms = options[:platforms].split(",").map(&:strip).reject(&:empty?)
  abort("--platforms needs at least one platform, for example bluesky,threads") if platforms.empty?

  body = { targets: [{ platforms: platforms }], text: options[:text] }
  body[:linkUrl] = options[:link] if options[:link]
  if options[:media]
    # A public https URL is fetched by Ampost; a local file is uploaded first.
    body[:media] = if options[:media].start_with?("https://")
                     [{ url: options[:media], type: options[:media_type] }]
                   else
                     [client.media.upload(options[:media])]
                   end
  end
  if options[:schedule]
    body[:scheduledFor] = options[:schedule]
  else
    body[:publishNow] = true
  end
  body
end

def main(argv)
  options = parse_options(argv)

  # The client reads AMPOST_API_KEY. It retries rate limits and server errors with the same
  # Idempotency-Key, so a retried request never posts twice.
  begin
    client = Ampost::Client.new
    post = client.posts.create(build_body(client, options), idempotency_key: options[:idempotency_key])
  rescue Ampost::Error => e
    # API errors read "400 VALIDATION_FAILED: ...": the status, Ampost's code and its message.
    # A missing AMPOST_API_KEY and a refused upload are Ampost::Error too.
    warn "Could not post: #{e.message}"
    return 1
  end

  puts "Post #{post["id"]} is #{post["status"]}"
  post["platformPosts"].each do |platform_post|
    puts "  #{platform_post["platform"]}: #{platform_post["status"]} #{platform_post["publishedUrl"]}".rstrip
  end
  0
end

exit(main(ARGV)) if $PROGRAM_NAME == __FILE__

Steps

  1. 1. Install the gem

    The SDK is the ampost gem on RubyGems. In a Rails app, add gem "ampost" to your Gemfile and run bundle install instead.

    terminal
    gem install ampost
  2. 2. Download the script and set your key

    Download post_with_sdk.rb above and put your API key in the AMPOST_API_KEY environment variable, where the SDK reads it. Keep the key out of your code and out of git.

    terminal
    export AMPOST_API_KEY=amp_live_your_key_here
  3. 3. Publish a post

    Run the script with the text and a comma-separated list of networks. Platform keys: instagram (Instagram), facebook (Facebook), linkedin (LinkedIn), tiktok (TikTok), threads (Threads), twitter (X), discord (Discord), telegram (Telegram), bluesky (Bluesky), youtube (YouTube), pinterest (Pinterest).

    It prints the new post's id and status, then one line per account.

    terminal
    ruby post_with_sdk.rb --text "Hello from Ruby and Ampost!" --platforms bluesky,threads
  4. 4. Add a link, an image or a schedule

    --link attaches a link and --schedule publishes later instead of now. --media takes a local image or video, which the SDK uploads first, or a public https URL (with --media-type image or video) that Ampost fetches; either way Ampost fits it to each network.

    Posting clips from a video or clipping tool? Video and clipping tools lists the Reels and Shorts options and each network's video limits.

    terminal
    ruby post_with_sdk.rb --text "New article" --platforms threads,bluesky --link https://example.com/post
    ruby post_with_sdk.rb --text "Launch day" --platforms instagram,facebook --media launch.jpg
    ruby post_with_sdk.rb --text "See you tomorrow" --platforms bluesky --schedule 2027-01-14T15:00:00Z
  5. 5. Call it from Rails

    client.posts.create(body) returns the post as a Hash with string keys. The body uses the API's field names (publishNow, scheduledFor). Pass your own idempotency_key:, for example your record's id, so a retried job never posts twice.

    The client opens a connection per request, so one client can be shared between threads and jobs.

    app/jobs/share_article_job.rb
    class ShareArticleJob < ApplicationJob
      def perform(article)
        client = Ampost::Client.new # reads AMPOST_API_KEY
        post = client.posts.create(
          { text: article.title, linkUrl: article.url, targets: [{ platforms: ["bluesky", "threads"] }], publishNow: true },
          idempotency_key: "article-#{article.id}"
        )
        article.update!(ampost_post_id: post["id"])
      end
    end

How errors are handled

The SDK retries RATE_LIMITED and server errors, waiting for the Retry-After header, and sends the same Idempotency-Key each time: a request that reached Ampost before a timeout is never posted twice.

Other errors raise a subclass of Ampost::APIError with Ampost's code and message, for example Ampost::BadRequestError with VALIDATION_FAILED, or Ampost::PermissionDeniedError with UPGRADE_REQUIRED when your plan lacks a feature. The script prints them as Could not post: .... The codes are in the API reference.

Without the gem

If you can't add a gem, the whole call is POST https://api.ampost.io/api/posts with net/http from the standard library. Unlike the SDK, this sends the request once, with no retries:

post.rb
require "json"
require "net/http"
require "securerandom"

uri = URI("https://api.ampost.io/api/posts")
request = Net::HTTP::Post.new(uri)
request["Authorization"] = "Bearer #{ENV.fetch("AMPOST_API_KEY")}"
request["Content-Type"] = "application/json"
request["Idempotency-Key"] = SecureRandom.uuid
request.body = JSON.generate({ targets: [{ platforms: ["bluesky", "threads"] }], text: "Hello!", publishNow: true })

response = Net::HTTP.start(uri.host, uri.port, use_ssl: true) { |http| http.request(request) }
raise "#{response.code}: #{response.body}" unless response.is_a?(Net::HTTPSuccess)
puts JSON.parse(response.body)["id"]

FAQ

Is there an Ampost Ruby SDK?

Yes. The ampost gem is on RubyGems (gem install ampost): every endpoint, retries, idempotency keys, typed errors, pagination and a one-call media upload, with no runtime dependencies. The code is at github.com/ampost-io/ampost-ruby.

Does it work with Rails?

Yes. Add gem "ampost" to your Gemfile and call client.posts.create from a controller, a model callback or a background job. One client can be shared between threads.

Do I need a developer account on each social network?

No. You connect each account to Ampost once in the dashboard, and the script only needs your Ampost API key.

Which social networks can I post to from Ruby?

Every network you connect to Ampost: Instagram, Facebook, LinkedIn, TikTok, Threads, X, Discord, Telegram, Bluesky, YouTube, Pinterest. Name them by key in targets[].platforms; X is twitter. LinkedIn and TikTok are coming soon.

Can I schedule a post instead of publishing it now?

Yes. Send scheduledFor with an ISO 8601 time (for example 2027-01-14T15:00:00Z) instead of publishNow: true, and Ampost publishes it then. Scheduling needs the Pro plan or higher.

What happens if the same request is sent twice?

The templates send an Idempotency-Key header. A retry with the same key within 24 hours returns the first post instead of creating a second one, so a retried step never posts twice.