Class: OpenaiAds::AdvertiserApiClient

Inherits:
BaseService show all
Defined in:
app/services/openai_ads/advertiser_api_client.rb

Overview

Service object: advertiser API client.

Constant Summary collapse

BASE_URL =

URL for base.

'https://api.ads.openai.com/v1'
PAGE_LIMIT =

Page size for the campaigns list endpoint. The API caps at 500,
which is well above the realistic active-campaign count for one
ad account (Google Ads parallel runs ~50 campaigns) so we expect
a single page in the common case.

500

Instance Attribute Summary

Attributes inherited from BaseService

#options

Instance Method Summary collapse

Methods inherited from BaseService

#initialize, #log_debug, #log_error, #log_info, #log_warning, #logger, #process, #tagged_logger

Constructor Details

This class inherits a constructor from BaseService

Instance Method Details

#list_campaigns(token:) ⇒ Array<Hash>

List all campaigns on the ad account. Walks the cursor pagination
until has_more is false and returns the concatenated list.

Parameters:

  • token (String)

    OpenAI Ads API key (bearer).

Returns:

  • (Array<Hash>)

    campaign objects per OpenAI's spec —
    id, name, status ("active"|"paused"|"archived"),
    created_at/updated_at (Unix timestamps), start_time/
    end_time, budget, targeting, etc.

Raises:

  • (Faraday::Error)

    on persistent transport errors after the
    normal Faraday retry budget.



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'app/services/openai_ads/advertiser_api_client.rb', line 41

def list_campaigns(token:)
  campaigns = []
  cursor    = nil

  loop do
    response = connection(token).get('campaigns') do |req|
      req.params['limit'] = PAGE_LIMIT
      req.params['after'] = cursor if cursor
      req.params['order'] = 'asc'
    end

    unless response.status == 200
      body = safe_parse(response.body)
      msg  = body['message'] || body['error'] || "HTTP #{response.status}"
      raise "OpenaiAds::AdvertiserApiClient: list_campaigns failed (HTTP #{response.status}): #{msg}"
    end

    body = safe_parse(response.body)
    page = Array(body['data'])
    campaigns.concat(page)

    break unless body['has_more']

    cursor = body['last_id'] || page.last&.dig('id')
    break unless cursor # defensive — `has_more` true with no cursor would loop forever
  end

  campaigns
end