Skip to content

How to Use a Service Account to Call the Google Ads API with Golang

Published: at 12:24 PM

It’s strongly not recommended to use service account to call the Google Ads API. The best practice is to use OAuth 2.0 for authentication. This post is for educational purposes only.

https://github.com/shenzhencenter/google-ads-pb is an unofficial Google Ads API Golang client library. I am the author of this library but I am not engineer of Google.

Table of contents

Open Table of contents

Introduction

In this post, I will show you how to authenticate your application using a service account and call the Google Ads API using the unofficial Google Ads API Golang client library(https://github.com/shenzhencenter/google-ads-pb).

Service account is a special type of Google account that belongs to your application or a virtual machine (VM), instead of to an individual end user. You can use a service account to impersonate a user in your Google Workspace domain and access the Google Ads API on behalf of the user.

Step 1: Enable Google Ads API on the Google Cloud Platform

Before you use the Google Ads API, you need to enable it on the Google Cloud Platform. To enable the Google Ads API, you can click https://console.cloud.google.com/apis/library/googleads.googleapis.com and enable the Google Ads API.

Google Ads API

Step 2: Create a Service Account

  1. Go to the Google Cloud Console and create a new service account.

Create a Service Account

  1. After creating the service account, you should generate a new key for the service account and download the JSON key file. This file will be used to authenticate your application. Copy the JSON key file to your project directory.

Generate a Key for the Service Account

  1. Copy the Client ID of the service account. You can find the Client ID in Advanced settings. You will need this Client ID to enable domain-wide delegation.

  2. Enable domain-wide delegation for the service account. This allows the service account to access the Google Ads API on behalf of users in your Google Workspace domain. To enable domain-wide delegation, go to the Google Workspace Admin Console. Click on Add new and enter the Client ID of the service account. The oauth scopes you need to add are: https://www.googleapis.com/auth/adwords.

Enable Domain-wide Delegation

From now on, all of settings are done. You can use the service account to authenticate your application and call the Google Ads API.

Step 3: Write Code to Call the Google Ads API

  1. Once you enable domain-wide delegation, you can use the service account to authenticate your application. Here is an example code snippet to authenticate your application.

const (
  // The path to the JSON key file
  KeyPath = "./xxx-xxxx-xxxxxxxxx.json"
  // The email address of the user you want to impersonate
  Subject = "[email protected]"
  // The scope of the Google Ads API
  Scope = "https://www.googleapis.com/auth/adwords"
)

// Load the JSON key file
jsonCredentials, err := os.ReadFile(KeyPath)
if err != nil {
	log.Fatalf("failed to read credentials: %v", err)
}

// Create a JWT config
config, err := google.JWTConfigFromJSON(jsonCredentials, Scope)
if err != nil {
	log.Fatalf("failed to load credentials: %v", err)
}
// Set the subject as the email address of the user you want to impersonate
config.Subject = Subject
// Get the token source
tokenSource := config.TokenSource(context.Background())
token, err := tokenSource.Token()
if err != nil {
	log.Fatalf("failed to get token: %v", err)
}

// The access token to authenticate your application
accessToken := token.AccessToken
  1. Now you can use the access token to call the Google Ads API. Here is an example code snippet to call the Google Ads API.
const (
  Endpoint = "googleads.googleapis.com:443"
  DeveloperToken = "xxxxxxxxxxxxxxxxxxxxx"
)

// Create a gRPC connection to the Google Ads API
cred := grpc.WithTransportCredentials(credentials.NewClientTLSFromCert(nil, ""))
conn, err := grpc.Dial(Endpoint, cred)
if err != nil {
	panic(err)
}
defer conn.Close()

// Create a context with the access token
ctx := context.Background()
headers := metadata.Pairs(
	"developer-token", DeveloperToken,
	"authorization", "Bearer "+accessToken,
)
ctx = metadata.NewOutgoingContext(ctx, headers)

// Call the Google Ads API
svc := services.NewCustomerServiceClient(conn)
req := &services.ListAccessibleCustomersRequest{}
resp, err := svc.ListAccessibleCustomers(ctx, req)
if err != nil {
	apiErr := status.Convert(err)
	log.Fatalf("code: %s, message: %s, details: %v",
    apiErr.Code(),
    apiErr.Message(),
    apiErr.Details(),
  )
}

// Print the customer IDs
for _, customer := range resp.ResourceNames {
	log.Println(customer)
}

The above code will print the customer IDs of the accessible customers in your Google Ads account. If it works, you have successfully authenticated your application using a service account and called the Google Ads API with Golang.

That’s it! I hope this post helps you understand service account. If you have any questions, contact me via email.

Happy coding!