How to Get Started With Google Ads API

Introduction

Google Ads is Google’s online advertising platform, allowing businesses to display ads on Google search results and across its network of partner websites. The Google Ads API provides a programmatic way to interact with your Google Ads campaigns, enabling tasks such as creating ads, adjusting bids, and retrieving performance reports. Whether you’re managing large accounts or need precise control, the API offers flexibility beyond the standard Google Ads interface. In this guide, we’ll walk you through the steps of connecting to the Google Ads API and making your first call.

Prerequisites

Before you dive into the details of using the Google Ads API, it is critical to ensure that you are prepared with the necessary tools and access rights. Below is a checklist of what you need:

Google Cloud Project (GCP): A GCP project provides the framework to access Google’s cloud services. You will need an active GCP project to create the necessary resources for connecting to the Google Ads API.

Google Ads Standard Account linked to Google Ads Manager Account (MCC): To use the Google Ads API, the Standard Google Ads account you want to interact with must either be linked to a Google Ads Manager account (MCC) or you must have permissions to create an MCC and link the account yourself.

Basic understanding of GCP, Google Ads, and Coding: While this guide will provide step-by-step instructions, a foundational understanding of Google Cloud Platform, Google Ads, and some basic coding knowledge will help you follow along more effectively.

High-Level Overview

To successfully make your first API call with the Google Ads API, you need to gather these crucial credentials:

  • Developer Token: Found in your Google Ads Manager account. Identifies you as a developer.
  • Google Cloud Platform (GCP) Project Credentials:
    • Client ID: Publicly identifies your application.
    • Client Secret: Confidential string to verify your application’s identity.
    • Refresh Token: To obtain new access tokens when they expire.

Once you’ve obtained these credentials, we will follow these general steps:

  • Install Client Library: Choose the Google Ads API client library for your preferred language (Python in our case).
  • Configure Authentication: Load your credentials into the library to authorize it.
  • Interact with the API: Utilize the library’s functions to retrieve data, manage campaigns, and perform actions within your Google Ads account.

With that said, we’ll spend most of our time in this article focused on obtaining all the necessary credentials and setting everything up for the first time, as this is often the most challenging aspect of working with any API.

STEP I. CREATE GOOGLE ADS MANAGER ACCOUNT (MCC)

Feel free to skip if you already have one.

  1. Navigate to the Google Ads Manager Account creation page.
  2. Select “Create a Manager Account”.

Follow the instructions above for setting up your account, which will include providing an account name and link it to the account that you wish to manage.

STEP II. Obtaining Your Developer Token

Navigating the process of obtaining a Developer Token for the Google Ads API can be somewhat complex, especially if you’re experienced with APIs that typically use only Service Accounts secrets, like the Google Analytics 4 API. For Google Ads API, you also need to secure a Developer Token. The necessity for this additional security measure arises because Google Ads accounts, unlike Google Analytics properties, have the capability to initiate and manage ad campaigns that may incur costs. Google introduced this requirement to mitigate the risk of misuse or unauthorized access to the API. What’s more, Google has instituted three levels of developer token access: test access, basic access, and standard access.

Initially, you will be granted test access, permitting API calls only to test accounts. This requires you to set up both a Test Google Ads Manager account (MCC) and a linked Test Standard Google Ads account. One important note is that an email linked to a production account (such as [email protected] , which is already running real campaigns) cannot be used for creating test accounts. Instead, you must register a different email (like [email protected] ) with Google Ads. After this registration, you can proceed to create both the test MCC account and test Standard account. Instructions for creating test accounts can be found here. While it’s possible to operate entirely within a test environment, these accounts contain no real or dummy data, which limits their practical utility. In this article, I will assume that you’ll be moving to Basic access.

To obtain your Developer Token for the Google Ads API, please follow these steps:

  1. Go to Tools & Settings -> API Center within your Google Ads MCC account.
  2. Fill out the necessary fields regarding your application and your planned use of the API. The form is straightforward, assuming a clear purpose for your API use. If any questions arise, it’s wise to consult Gemini LLM and official Google documentation.
  3. Agree to the Terms and Conditions.
  4. Click “Create Token” to generate your token.

For Basic Access to your Developer Token, follow these additional steps:

  • Select “Apply for Basic Access” and provide detailed information about your intended use of the Google Ads API. If you require further clarification, consultation with Gemini LLM and official Google documentation could be useful. Allow some processing time for Google to review your application. This may take several days.

Note, Basic access provides a quota of 15,000 API calls per day, sufficient for most users. If you need to exceed this limit, you’d then need to apply for Standard Access. Overall, the process of obtaining Basic Access is straightforward and simply involves filling out a form and waiting a few days for approval. Feel free to pause here and resume once you have received approval for your Basic access.

STEP II. OBTAINING SERVICE ACCOUNT CREDENTIALS

Next, you must enable the API in your Google Cloud Platform (GCP) account and obtain the necessary credentials. Here’s how to do both:

Enable Google Ads API:

  1. Project Dashboard: Access your Google Cloud Project dashboard.
  2. APIs & Services: Navigate to the “APIs & Services” section.
  3. Search and Enable: Look for “Google Ads API” and click “Enable.”

Getting Client ID and Client Secret

First of all, you would need to have Google Cloud Platform (GCP) account and then from GCP Console you need to have a project. If you don’t have any projects, while on GCP Console click on “Create New Project,” give it a name, specify billing, and location of it. Once, it is done:

  1. Configure OAuth Consent Screen: Inside you project Dahsboard, find “Credentials” (API & Services) using Search Bar. Then, click on “Create Credentials” -> “OAuth Client ID.” After that, click on “Configure Consent Screen.” You’d be required to choose between User Type. In essence if you only want users within your organization to use it then you need to choose “Internal”, if you want to allow anyone to use then you need to use “External.” In our example, we choose “External.” After that, you would need to go through “OAuth consent screen” -> “Scopes” -> “Test Users” -> “Summary.” For “OAuth consent screen,” you need to provide App name, which can be whatever you want. Then, within “Scopes,” you need to click “Add or Remove Scopes”, select “Google Ads API” and click “Update.” After that, you can click “Save & Continue” for both “Scopes” and “Test Users.”
  2. Create OAuth Credentials: Inside of “API & Services/ Credentials,” click “Create Credentials” -> “OAuth client ID.” You need to select type of application, let’s say we proceed with “Web Application.” Then, you need to give it a name which can be whatever you want. For “Authorized JavaScript Origins” & “Authorized redirect URIs” you can put “htpps://127.0.0.1” which is your local host. Again, it makes sense for us. Since, we describing introductory case. When, you switch to production, you would need to change this. After that click on “Create.” This should output window with your “Your Client ID” and “Your Client Secret.” Click on “Download JSON” and save your credentials in some safe place. Since this is introductory level article we save credentials into json file named “client_secrets.json” in the folder named “Google Ads API” on our desktop.
  3. Publish App: In the next screen, click on “Publish App,” then click “Confirm.”

Please be aware that because Google Ads is classified as a sensitive scope, your app will be marked as unverified. This will initially limit your user base to 100 and result in complex consent screens later. I advise verifying your app. To do this, go to ‘API & Services’ -> ‘Credentials.’ There, you will see a notice stating, ‘To protect you and your users, your consent screen and application need to be verified by Google.’ You should click on ‘Configure Consent Screen,’ where you’ll be prompted to provide details about your application. The process is generally straightforward. If you are unsure, consider consulting Gemini LLM and official Google documentation. Note that verification isn’t required to proceed with the rest of the article, so you can finalize your setup now and seek verification later.

Security Note

Please note that all credentials we created above should be stored securely and should not be shared with anyone (even your cat). These credentials grant access to your Google Ads account, and compromising them could lead to unauthorized modifications or charges. I recommend using Google Secret Manager or a similar secure credential management solution to store these credentials safely.

STEP III. How To Make Your First API Call

This part demonstrates how to make API calls to Google Ads API from your local machine (Mac), which is a great starting point.

Step 1: Install Client Library: For sake of this tutorial we would assume that you have Python (version 3.8 or higher) on your local machine. It is a recommended approach to use virtual environments to work with your APIs. You can think of virtual enviroments as project where you can specify what version of language and its dependencies you need. This is useful since allow us avoid clashes between different projects on your machine. We will use venv package to create and manage python virtual environments. First, we need to create virtual environment. To do so, please open Terminal at the folder that belongs to your Google Ads API project i.e. “Google Ads API” in our case. Namely, you would need to right click on the folder from the menu shown pick Services -> “Open terminal at folder.” Then type the following:

python3 -m venv googleAdsApi 
source googleAdsApi/bin/activate
pip install google-ads

Here, “googleAdsApi” is just name of your environment. It can be anything you want. First line of code creates virtual environment, second line is activating it. Third line installs “google-ads” library directly into the “googleAdsApi” virtual environment.

**Step 2: Download Git Hub Repo with examples to play with: ** First, you would need to get the absolute path to our “client_secrets.json” file that we created earlier. To get absolute path, you can right click on file, press “Option” button, and then pick “client_secrets.json’ as PathName.” Then, in the same terminal window as we typed our previous command input the following and don’t forget to insert absolute path to JSON that you copied previously instead of {path}.

git clone https://github.com/googleads/google-ads-python.git

cd google-ads-python/examples/authentication

python3 generate_user_credentials.py \
--client_secrets_path="{path}" 

This should do 3 things. First, it will install the code examples that we need. Secondly, it will move us toward folder where the code that we want to run is located. Lastly, it will run the program and give it path to credentials to use. If everything run successfully, then it should output the URL to paste into browser.

**Step 3: Getting Refresh Token: ** Copy the URL outputed in Terminal, and input it into Chrome Incognito Window. It should return page where it asks you sure you want to allow this app permissions to your Google Ads. Please note that if you haven’t verified your app, it window will state “This app is not verified.” Since this app is created by us, we can trust it. So, we need to click on “Advanced,” then allow. This should tell you something like: “Authorization code was successfully retrieved. Please check the console output.” Which means we did all right and we can open again our Terminal window where we can find our refresh token, after the text: “Your refresh token is:”. Make sure to copy it somewhere safe.

**Step 4: Saving all credentials in yaml file: ** Our next step would be to create the “google-ads.yaml” file within the “Google Ads API” folder. Make it content like the following:

developer_token: INSERT_DEVELOPER_TOKEN_HERE
use_proto_plus: INSERT_USE_PROTO_PLUS_FLAG_HERE
client_id: INSERT_OAUTH2_CLIENT_ID_HERE
client_secret: INSERT_OAUTH2_CLIENT_SECRET_HERE
refresh_token: INSERT_REFRESH_TOKEN_HERE
login_customer_id: INSERT_LOGIN_CUSTOMER_ID_HERE

In this step, you need to substitute the given values with the credentials we previously established. Choose either True or False for the use_photo_plus option; we have selected True. Next, enter the MCC account’s ID into the login_customer_id field. This ID typically appears as a 10-digit number formatted like XXX-XXX-XXXX when you log into your MCC account in Google Ads. It’s important to include this number in the yaml file without any hyphens. Once this is completed, copy the absolute path of the yaml file, as we’ll need it for the next step.

**Step 5: Preparing our first script to run: ** Next, to actually run other example files from library we need to create GoogleAdsClient instance which we can do by running it’s built in method GoogleAdsClient.load_from_storage as an argument we need to provide the path to our Yaml file. Please make sure to insert absolute path we copied previously instead of {path} in the code snippet below.

import os

os.environ["GOOGLE_ADS_CONFIGURATION_FILE_PATH"] = "{path}"
from google.ads.googleads.client import GoogleAdsClient
client = GoogleAdsClient.load_from_storage()

Please be aware that to execute any code examples from the library we installed, we must include the aforementioned lines of code at the beginning of each code snippet we intend to run. Below is an example of how the get_campaigns.py file will appear after our modifications.

# Import statement above
import os

os.environ["GOOGLE_ADS_CONFIGURATION_FILE_PATH"] = "{path}"
from google.ads.googleads.client import GoogleAdsClient
client = GoogleAdsClient.load_from_storage()

# Actual lines of code
import argparse
import sys

from google.ads.googleads.client import GoogleAdsClient
from google.ads.googleads.errors import GoogleAdsException

# [START get_campaigns]
def main(client, customer_id):
    ga_service = client.get_service("GoogleAdsService")

    query = """
        SELECT
          campaign.id,
          campaign.name
        FROM campaign
        ORDER BY campaign.id"""

    # Issues a search request using streaming.
    stream = ga_service.search_stream(customer_id=customer_id, query=query)

    for batch in stream:
        for row in batch.results:
            print(
                f"Campaign with ID {row.campaign.id} and name "
                f'"{row.campaign.name}" was found.'
            )
            # [END get_campaigns]


if __name__ == "__main__":
    # GoogleAdsClient will read the google-ads.yaml configuration file in the
    # home directory if none is specified.
    googleads_client = GoogleAdsClient.load_from_storage(version="v16")

    parser = argparse.ArgumentParser(
        description="Lists all campaigns for specified customer."
    )
    # The following argument(s) should be provided to run the example.
    parser.add_argument(
        "-c",
        "--customer_id",
        type=str,
        required=True,
        help="The Google Ads customer ID.",
    )
    args = parser.parse_args()

    try:
        main(googleads_client, args.customer_id)
    except GoogleAdsException as ex:
        print(
            f'Request with ID "{ex.request_id}" failed with status '
            f'"{ex.error.code().name}" and includes the following errors:'
        )
        for error in ex.failure.errors:
            print(f'\tError with message "{error.message}".')
            if error.location:
                for field_path_element in error.location.field_path_elements:
                    print(f"\t\tOn field: {field_path_element.field_name}")
        sys.exit(1)

Step 6: We (finally!) making our API call: Before running our code, I need you to obtain one more piece of information. You must fetch the Customer ID and substitute ‘{customer_id}’ with it in the code snippet below. The Customer ID is the identifier for the Google Ads Standard Account from which we need to pull data. Remember, our MCC account controls various standard Google Ads accounts. To access the data we require, the Google Ads API must identify the particular standard account we are referencing. After you get that piece of data, you need to proceed in the terminal to the folder where get_campaigns.py located. You can do it by running the following commands:

cd ..
cd basic_operations

Then, run the following:

python3 get_campaigns.py -c {customer_id}

Hopefully, it should output the list of campaigns in the specified account.

Conclusion

Okay, getting a list of campaigns might not seem like a huge feat after all that setup we done, but take a moment to appreciate it – this is where those API skills begin to pay off! This article was all about providing a clear starting point to using the Google Ads API. Keep exploring those Google docs, experimenting, and build scripts that will streamline your campaign management. The initial setup is often the most time-consuming part – you’re past that now! If you found value in this guide, pass it along so others can start their API learning journey as well.


If you found this article useful and would like to support my work, consider buying me a coffee! Just click on the button below and follow the instructions to make a donation. Your support helps me create more valuable content. Thank you!