> ## Documentation Index
> Fetch the complete documentation index at: /docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Use Importly in Rails with Active Job

> Transcribe or download any video or audio link from a Rails app with Active Job, with retries that respect rate limits and never start the same job twice. Works with Sidekiq, Solid Queue and GoodJob.

If your Rails app takes video or podcast links, the media job is the one that breaks once it runs on a server: sites block datacenter IPs, and many videos have no captions to read. Call Importly from the job instead. It returns the transcript, a download link for the file, or the video's details, for links from YouTube, TikTok, Instagram, X, podcasts and 1,000+ other sites.

Long imports can take a few minutes, so don't hold a worker for them. One job starts the Importly job and stores its ID, and a second job checks the status and enqueues itself again 20 seconds later until it's done. A retry only ever re-runs the check, so it never starts the job twice. The code uses plain Active Job and `Net::HTTP`, so it runs on Sidekiq, Solid Queue, GoodJob or any other backend.

## 1. Add your key

Create your key on the [API key page](https://www.importly.io/dashboard/api-key) (it is shown once). Add it as `IMPORTLY_API_KEY` to the environment your app and job workers run in, and to `.env` (or your credentials) for development:

```bash .env theme={null}
IMPORTLY_API_KEY=your_api_key
```

The jobs below save to a `Video` model with `url`, `importly_job_id`, `importly_status`, `importly_result` (json) and `importly_error` columns:

```bash theme={null}
bin/rails generate migration AddImportlyToVideos importly_job_id:string importly_status:string importly_result:json importly_error:string
```

## 2. A small client

A `429` raises `RetryLater` with the `retryAfter` the API sent, and a `5xx` raises it with 30 seconds. A `400` (a bad link), `401` (a wrong key) or `402` (balance too low) won't change on a retry, so it raises `Rejected` and the job fails:

```ruby app/services/importly.rb theme={null}
require "json"
require "net/http"

module Importly
  API = URI("https://api.importly.io")

  # A 429 or 5xx: the same request can work after `seconds`
  class RetryLater < StandardError
    attr_reader :seconds

    def initialize(message, seconds)
      super(message)
      @seconds = seconds
    end
  end

  # A 400 (bad link), 401 (wrong key) or 402 (balance too low): a retry won't change it
  class Rejected < StandardError; end

  def self.call(path, body = nil)
    uri = URI.join(API, path)
    request = body ? Net::HTTP::Post.new(uri) : Net::HTTP::Get.new(uri)
    request["Authorization"] = "Bearer #{ENV.fetch("IMPORTLY_API_KEY")}"
    request["Content-Type"] = "application/json"
    request.body = body.to_json if body

    # read_timeout is longer than the 30-second wait on /transcribe
    response = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https", read_timeout: 70) do |http|
      http.request(request)
    end
    json = JSON.parse(response.body)
    return json["data"] if response.is_a?(Net::HTTPSuccess) && json["success"]

    message = "Importly #{response.code} #{json["code"]}: #{json["error"] || "request failed"}"
    status = response.code.to_i
    raise RetryLater.new(message, (json["retryAfter"] || 60).to_i) if status == 429
    raise RetryLater.new(message, 30) if status >= 500
    raise Rejected, message
  end
end
```

## 3. The jobs

A shared base class waits for `retryAfter` on a `429`, up to 5 tries, and saves the outcome:

```ruby app/jobs/importly_job.rb theme={null}
# Shared by the jobs below: wait for retryAfter on a 429, up to 5 tries
class ImportlyJob < ApplicationJob
  rescue_from(Importly::RetryLater) do |error|
    raise error if executions >= 5
    retry_job(wait: error.seconds)
  end

  STATUS_PATH = { "transcribe" => "/transcribe/status", "import" => "/import/status" }.freeze

  private

  def finish_or_check(video, kind, job)
    video.update!(importly_job_id: job["jobId"], importly_status: job["status"])
    if %w[queued running].include?(job["status"])
      CheckImportlyJob.set(wait: 20.seconds).perform_later(video.id, kind, job["jobId"])
    else
      save_result(video, job)
    end
  end

  def save_result(video, job)
    if job["status"] == "completed"
      # a transcript has result["text"]; an import has result["mediaUrl"], valid for 7 days
      video.update!(importly_status: "completed", importly_result: job["result"])
    else
      video.update!(importly_status: "failed", importly_error: "#{job["code"]}: #{job["message"]}")
    end
  end
end
```

`"mode": "auto"` uses the video's captions and falls back to speech-to-text when it has none. `wait: true` holds the request open for up to 30 seconds, so a transcript from captions usually comes back from the first call and is saved straight away:

```ruby app/jobs/transcribe_link_job.rb theme={null}
class TranscribeLinkJob < ImportlyJob
  def perform(video_id)
    video = Video.find(video_id)
    job = Importly.call("/transcribe", {
      url: video.url,
      mode: "auto", # captions, or speech-to-text when there are none
      wait: true, # captions usually come back within the 30-second wait
      maxCostDollars: 1
    })
    finish_or_check(video, "transcribe", job)
  end
end
```

`POST /import` returns a job ID straight away:

```ruby app/jobs/import_link_job.rb theme={null}
class ImportLinkJob < ImportlyJob
  def perform(video_id, audio_only: false)
    video = Video.find(video_id)
    job = Importly.call("/import", {
      url: video.url,
      includeVideo: !audio_only,
      videoQuality: "720p", # a ceiling: lower if the source has no 720p
      maxCostDollars: 0.5 # the most this one file may cost
    })
    finish_or_check(video, "import", job)
  end
end
```

Anything still `queued` or `running` goes to the check job:

```ruby app/jobs/check_importly_job.rb theme={null}
# Checks every 20 seconds, for up to an hour
class CheckImportlyJob < ImportlyJob
  def perform(video_id, kind, job_id, checks = 1)
    video = Video.find(video_id)
    job = Importly.call("#{STATUS_PATH.fetch(kind)}?id=#{CGI.escape(job_id)}")
    if %w[queued running].include?(job["status"]) && checks < 180
      self.class.set(wait: 20.seconds).perform_later(video_id, kind, job_id, checks + 1)
    elsif %w[queued running].include?(job["status"])
      video.update!(importly_status: "failed", importly_error: "still #{job["status"]} after an hour")
    else
      save_result(video, job)
    end
  end
end
```

A finished transcript's `importly_result` has `text`, and `data.segments` with `start` and `end` times in seconds. A finished import's has `mediaUrl`, a link to the file that's valid for 7 days: attach it with Active Storage or copy it to your bucket if you keep it, or connect your bucket once and import with `store: true` ([Save to your bucket](/docs/integrations/save-to-bucket.md)). A caption transcript costs \$0.003; speech-to-text is billed per minute, and `maxCostDollars` caps what one link can cost. See [Transcripts](/docs/features/transcripts.md) and [Downloads](/docs/features/downloads.md).

## Run it

Enqueue the job from your controller once the record is saved:

```ruby app/controllers/videos_controller.rb theme={null}
def create
  video = Video.create!(url: params.require(:url))
  TranscribeLinkJob.perform_later(video.id)
  redirect_to video
end
```

## Notes

`SOURCE_THROTTLED` and `LIVE_NOT_SUPPORTED` are the failure codes that can work on a later attempt (a stream that is still live, or a site that is busy for now). For those, enqueue `TranscribeLinkJob` or `ImportLinkJob` again later; every other failure code is final. See [Media unavailable](/docs/errors/media-unavailable.md) and [Source throttled](/docs/errors/source-throttled.md).

`POST /import` allows 240 requests per hour per key, and an account can have 50 imports queued or running at once. Status endpoints allow 3,600 requests per hour per job type; a check every 20 seconds is 180 an hour for each job in progress, so about 20 jobs can poll at once. With Sidekiq or Solid Queue, put these jobs on their own queue with a concurrency limit. For hundreds of links, see [Batch imports](/docs/integrations/batch-imports.md).

Prefer a webhook? Start the job with a `webhookUrl`, check the `Importly-Signature` header on the raw body (`request.raw_post`) as shown in [Verify signatures](/docs/webhooks.md#verify-signatures), then read the job by its `jobId` with `Importly.call`. Each job gets one delivery and no retries, so keep the check job as a fallback for jobs that stay pending.

A `youtube.com/playlist?list=…` link is rejected with `PLAYLIST_NOT_SUPPORTED`. Enqueue one job per video instead.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.