Convert SRT to VTT with Ruby

Convert subtitle formats in Ruby with the SubtoVTT API. Standard-library net/http example. Free API key, 100 credits to start. v1 · stable

Convert SRT to VTT with Ruby using only the standard library — net/http and a hand-built multipart body. No gems, no setup.

Pick Ruby when you're inside a Rails app, a Rake task, or any script where you'd rather not add an HTTP gem for a single request.

Convert SRT to VTT

require "net/http"
require "uri"

api_url = URI("https://api.example.com/api/v1/convert")
api_key = ENV.fetch("SUBTOVTT_API_KEY")

boundary = "----SubtoVTT#{rand(1_000_000)}"
content = File.binread("movie.srt")

body = +""
body << "--#{boundary}\r\n"
body << "Content-Disposition: form-data; name=\"file\"; filename=\"movie.srt\"\r\n"
body << "Content-Type: application/x-subrip\r\n\r\n"
body << content << "\r\n"
body << "--#{boundary}\r\n"
body << "Content-Disposition: form-data; name=\"from\"\r\n\r\nsrt\r\n"
body << "--#{boundary}\r\n"
body << "Content-Disposition: form-data; name=\"to\"\r\n\r\nvtt\r\n"
body << "--#{boundary}--\r\n"

request = Net::HTTP::Post.new(api_url)
request["Authorization"] = "Bearer #{api_key}"
request["Content-Type"] = "multipart/form-data; boundary=#{boundary}"
request.body = body

response = Net::HTTP.start(api_url.host, api_url.port, use_ssl: true) do |http|
  http.request(request)
end

unless response.code == "200"
  raise "Conversion failed: #{response.code} #{response.body}"
end

puts "Cues: #{response['X-Cue-Count']}"
File.binwrite("movie.vtt", response.body)

Ruby's net/http doesn't build multipart bodies for you, so the example assembles the boundary-delimited parts manually. The two parts that matter are file (with the filename attribute) and the from/to fields that select the conversion.

response.body is the converted file; File.binwrite writes it byte-for-byte to movie.vtt. X-Cue-Count in the response headers reports how many cues came out.

Note: keep use_ssl: true — the API only accepts HTTPS. Set SUBTOVTT_API_KEY first (100 free credits on key creation).

Convert between any formats

Next

↑ Back to top