LoginSignup
1
0

Google Ads APIをPythonで叩くときの勘所

Posted at

背景

  • Google Ads APIを叩いてRSA広告の実績を取得したいです

ドキュメント

  • 基本これを頑張って見ればいけます

認証まわり

これが一番大変です.
以下の4つの認証情報を集めるということを覚えておいてください.

  • developer_token
  • client_id
  • client_secret
  • refresh_token

login_customer_id

  • また広告のアカウントのlogin_customer_idも用意しておく必要があります
  • 対象の広告アカウントの管理画面の右上にある xxx-xxx-xxxx の数字です

スクリーンショット 2024-03-26 18.05.56.png

developer_token

  • MCCアカウントの [API センター] ページからトークンを取得できます
    • MCCアカウント: My Client Centerの略らしい. 広告アカウントのマネージャーアカウントみたいなものだと思います.
  • 広告担当の偉い人にお願いして発行してもらいましょう

client_id, client_secret

  • GCPの管理画面から発行できます. GCPの権限がない場合はエンジニアの偉い人にお願いしましょう.
  • まずは、OAuth同意画面で、OAuthにGoogle Ads APIのScopeを追加する設定をします
    • アプリはInternalデスクトップアプリにして作っていきます
  • その後、"認証情報"のOAuth2.0クライアントIDの画面からクレデンシャルのjsonをダウンロードしてください
    • このjson内にclient_idとclient_secretの値が書いてあります

スクリーンショット 2024-03-26 17.49.00.png

  • 以下のページの動画が非常にわかりやすいです

refresh_token

  • oauth2lというGoogle OAuth 2.0 を操作するコマンドライン ツール を利用して発行します
# oauth2lをインストールした後
# credentials.jsonを先ほどダウンロードした認証情報jsonです
oauth2l fetch --credentials credentials.json --scope adwords \
    --output_format refresh_token

出力

{
  "client_id": "******.apps.googleusercontent.com",
  "client_secret": "******",
  "token_uri": "https://oauth2.googleapis.com/token",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "refresh_token": "******",
  "type": "authorized_user"
}

google-ads.yamlを用意

ここからgoogle-ads.yamlをコピーして以下の値を置き換えてください.

  • client_id: INSERT_OAUTH2_CLIENT_ID_HERE
  • client_secret: INSERT_OAUTH2_CLIENT_SECRET_HERE
  • refresh_token: INSERT_REFRESH_TOKEN_HERE
  • developer_token: INSERT_DEVELOPER_TOKEN_HERE
  • login_customer_id: INSERT_LOGIN_CUSTOMER_ID_HERE
  • (INSERT_USE_PROTO_PLUS_FLAG_HEREはTrueでOK)

実装

# google-ads をインストール
python -m pip install google-ads==21.3.0
from google.ads.googleads.client import GoogleAdsClient
client = GoogleAdsClient.load_from_storage("./google-ads.yaml")
ga_service = client.get_service("GoogleAdsService")

query = """
SELECT
  campaign.id,
  ad_group.id,
  assset,
  metrics.impressions, 
  metrics.clicks,
  metrics.conversions
FROM ad_group_ad_asset_view
WHERE campaign.id = 'CAMPAIGN_ID'
"""

# Issues a search request using streaming.
# customer_idにはlogin_customer_idと同じものを使ってください
stream = ga_service.search_stream(customer_id="xxxx", query=query)

for batch in stream:
    for row in batch.results:
        print(row)
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0