SDKs

Ruby

Thunderbit Open API 的 Ruby 地道寫法

Net::HTTP(內建)或 Faraday(中介層風格的重試與逾時)。兩者都行 —— 下面用 Net::HTTP 示範。

設定

require 'net/http'
require 'json'
require 'uri'

API = 'https://openapi.thunderbit.com/openapi/v1'
HEADERS = {
  'Authorization' => "Bearer #{ENV.fetch('THUNDERBIT_API_KEY')}",
  'Content-Type'  => 'application/json'
}.freeze

def post(path, body)
  uri = URI("#{API}#{path}")
  res = Net::HTTP.post(uri, body.to_json, HEADERS)
  raise res.body if res.code.to_i >= 400
  JSON.parse(res.body)
end

Distill 一個頁面

result = post('/distill', { url: 'https://thunderbit.com/playground' })
puts result['data']['markdown']

Extract 結構化資料

result = post('/extract', {
  url: 'https://example.com/product/iphone-15-pro',
  schema: {
    type: 'object',
    properties: {
      name:  { type: 'string' },
      price: { type: 'number' }
    },
    required: %w[name price]
  }
})
puts result['data']

Batch + Sidekiq

非同步散發時,把提交丟進佇列,讓 Sidekiq worker 處理 Webhook 回呼:

class DistillBatchJob
  include Sidekiq::Worker

  def perform(urls)
    job = post('/batch/distill', {
      urls: urls,
      webhook: {
        url:    "#{ENV['APP_HOST']}/webhooks/distill",
        secret: ENV['WEBHOOK_SECRET']
      }
    })
    Rails.logger.info "Batch submitted: #{job['data']['id']}"
  end
end

在你的 Rails controller 裡驗證 Webhook 簽名 —— 參見 Webhooks

官方 Ruby SDK 開發中 —— 敬請期待。