How to generate image from Vertex AI and Upload to Google Ads

1. Introduction

What you'll build

In this codelab, You will learn how to generate images using Vertex AI and send it to Google Ads so that the assets can be used as image assets in the campaigns.

What you'll learn

  • How to generate images from GCP, Vertex AI
  • How to upload images to the Google Ads
  • How to use it in Google Ads

What you'll need

  • Google Ads Account
  • GCP Account

2. Get Google Ads credentials

This part is needed to get image assets from Google Ads. To access Google Ads from Colab, you need proper credentials.

Create credentials -> Create ‘OAuth client ID' -> Web Application

To get proper credentials to connect Google Ads, you need to access Cloud credentials.

If you haven't configured consent screen, setup consent screen first.

  1. User type: External
  2. Publishing status: In production


Add the following URI to ‘Authorized redirect URIs'

Put below URI as the below screenshot.


Copy Client ID and client secret

You can get client ID and client secret.


3. Generate Refresh Token

Access to OAuth Playground

You can easily issue a temporary refresh token at OAuth Playground.

Go to the settings, and check on the ‘User your own OAuth credentials'. After you acquired OAuth client ID and client secret from the previous chapter, you can put them into the corresponding text boxes. ace79f71603a922.png


Add the scope

You can add the scope into the below area.


Click Authorize APIs, and you will see the next screen.

Generate Refresh Token

Click ‘Exchange authorization code for tokens', and you will see the refresh token.


4. Prepare Colab for executing the code

Colab is the handy code notebook that comes with Python. The default option provides quite a generous amount of computing power. You can also use any platform to call the REST API of the Google Cloud Vertex AI.

Please go to to use it.

Go to [File → New note] and start writing new codes.


If you click New Notebook, you will see the new sheet ready for you.

5. Generate Image through Google Cloud Vertex AI

Import libraries

!pip install requests google-ads

First, Install libraries for Google Ads, and API requests. You need to restart runtime after installing the libraries.

You can also load essential libraries.

import requests
import json
import base64

from import googleads
from google.colab import auth
from IPython.display import display, Image

Get Authentication

You will be asked to authorize your google account.


access_token = !gcloud auth print-access-token
access_token = access_token[0]

After authorizing yourself, you are ready to call Google Cloud APIs.

6. Generate image from Vertex AI

Prepare your prompt and POST request

First, you should have your Google cloud project ID. You can get it from Google Cloud. You need a text prompt, and you can also set how many images you need. For more options, please refer to the official documentation.

PROJECT_ID = 'abcdefg' # Your GCP project ID
TEXT_PROMPT = 'cat computer' # Your prompt goes here.
IMAGE_COUNT = 4 # You will get 4 images as a result.

You can write anything inside the text prompt. Here, we want to generate the images that have cat and computer together in a single picture.

url = f"{PROJECT_ID}/locations/us-central1/publishers/google/models/imagegeneration:predict"

headers = {
    "Authorization": f"Bearer {access_token}",
    "Content-Type": "application/json; charset=utf-8"

data = {
    "instances": [
            "prompt": TEXT_PROMPT
    "parameters": {
        "sampleCount": IMAGE_COUNT

Request image generation

Once you are ready for the json, you can now request for the image generation. Below is the typical http request.

response =, headers=headers, data=json.dumps(data))

if response.status_code == 200:
    response_data = response.json()

    for prediction in response_data.get('predictions', []):
        image_data = base64.b64decode(prediction['bytesBase64Encoded'])
    print("Request failed:", response.status_code, response.text)

If you wait several seconds, you will get the result. Very simple!


7. Get Connected to Google Ads

Connect to your Google Ads Account

You need a developer token from Google Ads. You can apply for basic or standard dev token, but for the testing purpose, test token is also available. Go to your MCC account. In the tools and settings tab, you will see the API center. At the API section, you will find your token there.

Client id, client secret and refresh tokens should be ready at the previous chapter.

credentials = {
    "developer_token": "ABCDEFG",
    "client_id": "",
    "client_secret": "GOCSPX-abcd1234-abcd1234-abcd1234",
    "refresh_token": "1//abcdefghijklmnopqrstuvwxyz",
    "use_proto_plus": True

After setting credentials, you can load GoogleAdsService API. Customer id is usually in format of xxx-xxxx-xxx, but you should remove ‘-'.

client = googleads.client.GoogleAdsClient.load_from_dict(credentials, version='v13')
googleads_service = client.get_service("GoogleAdsService")
customer_id = "1234567890"

Querying Google Ads Account

Now, you can test with googleads_service. Let's query what kind of assets we have in the Ads account.

query = (
FROM ad_group_ad
response =, query=query)
for googleads_row in response:

You will see the list of assets in Google Ads account in json format. If you see something like

ad_group_ad {

`images { asset: "customers/1234567890/assets/09876543210" }` 


8. Upload Image Asset to Google Ads


For the last step, we are going to upload generated assets to Google Ads.

for prediction in response_data.get('predictions', []):
    image_base64 = prediction['bytesBase64Encoded']

    image_bytes = base64.b64decode(image_base64)

    asset_service = client.get_service('AssetService')
    asset_operation = client.get_type('AssetOperation')

    asset = asset_operation.create
    asset.type_ = client.enums.AssetTypeEnum.IMAGE = image_bytes = "cats"

    asset_service.mutate_assets(customer_id=customer_id, operations=[asset_operation])

After a few seconds, you will be able to check the uploaded asset through Google Ads Frontend. Here is the sample screenshot.


9. Congratulations

Congratulations, you've successfully generated beautiful image assets from the existing image!

You've learned

  • How to generate image assets through generative AI (Vertex AI)
  • How to upload images to Google Ads and use it as image assets