or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

ad-management.mdasset-management.mdaudience-management.mdbatch-operations.mdcampaign-management.mdclient-setup.mdconversion-tracking.mdindex.mdreporting-search.mdtargeting-keywords.md

client-setup.mddocs/

0

# Client Setup and Authentication

1

2

Core client initialization, configuration management, and authentication flows for the Google Ads Python client library. This includes OAuth2 flows, service account authentication, and various client configuration methods.

3

4

## Capabilities

5

6

### Client Initialization

7

8

The GoogleAdsClient provides multiple methods for initialization with different configuration sources.

9

10

```python { .api }

11

class GoogleAdsClient:

12

"""Google Ads client used to configure settings and fetch services."""

13

14

def __init__(

15

self,

16

credentials,

17

developer_token: str,

18

endpoint: str = None,

19

login_customer_id: str = None,

20

logging_config: dict = None,

21

linked_customer_id: str = None,

22

version: str = None,

23

http_proxy: str = None,

24

use_proto_plus: bool = False,

25

use_cloud_org_for_api_access: str = None

26

):

27

"""

28

Initialize GoogleAdsClient with credentials and configuration.

29

30

Parameters:

31

- credentials: Google OAuth2 credentials instance

32

- developer_token: Google Ads developer token

33

- endpoint: Optional alternative API endpoint

34

- login_customer_id: Login customer ID for API access

35

- logging_config: Dictionary with logging configuration

36

- linked_customer_id: Linked customer ID for API access

37

- version: API version to use (v19, v20, v21)

38

- http_proxy: Proxy URI for connections

39

- use_proto_plus: Use proto-plus message interfaces

40

- use_cloud_org_for_api_access: Use cloud org for access levels

41

"""

42

43

@classmethod

44

def load_from_storage(cls, path: str = None, version: str = None) -> 'GoogleAdsClient':

45

"""

46

Create client from YAML configuration file.

47

48

Parameters:

49

- path: Path to YAML file (defaults to google-ads.yaml)

50

- version: API version to use

51

52

Returns:

53

GoogleAdsClient initialized from file

54

55

Raises:

56

- FileNotFoundError: If configuration file doesn't exist

57

- ValueError: If configuration lacks required fields

58

"""

59

60

@classmethod

61

def load_from_env(cls, version: str = None) -> 'GoogleAdsClient':

62

"""

63

Create client from environment variables.

64

65

Parameters:

66

- version: API version to use

67

68

Returns:

69

GoogleAdsClient initialized from environment

70

71

Raises:

72

- ValueError: If environment lacks required variables

73

"""

74

75

@classmethod

76

def load_from_dict(cls, config_dict: dict, version: str = None) -> 'GoogleAdsClient':

77

"""

78

Create client from configuration dictionary.

79

80

Parameters:

81

- config_dict: Dictionary with configuration data

82

- version: API version to use

83

84

Returns:

85

GoogleAdsClient initialized from dictionary

86

87

Raises:

88

- ValueError: If dictionary lacks required fields

89

"""

90

91

@classmethod

92

def load_from_string(cls, yaml_str: str, version: str = None) -> 'GoogleAdsClient':

93

"""

94

Create client from YAML string.

95

96

Parameters:

97

- yaml_str: YAML configuration as string

98

- version: API version to use

99

100

Returns:

101

GoogleAdsClient initialized from YAML string

102

103

Raises:

104

- ValueError: If YAML lacks required fields

105

"""

106

```

107

108

### Service Access

109

110

Access to Google Ads API services through the client.

111

112

```python { .api }

113

def get_service(self, name: str, version: str = None, interceptors: list = None) -> object:

114

"""

115

Get a service client instance for the specified service.

116

117

Parameters:

118

- name: Service name (e.g., "CampaignService", "GoogleAdsService")

119

- version: API version override (v19, v20, v21)

120

- interceptors: Optional list of custom interceptors

121

122

Returns:

123

Service client instance for the specified service

124

125

Raises:

126

- ValueError: If service doesn't exist in specified version

127

"""

128

```

129

130

### Configuration Management

131

132

Configuration loading and validation utilities.

133

134

```python { .api }

135

# Configuration functions

136

def load_from_env() -> dict:

137

"""

138

Load configuration from environment variables.

139

140

Returns:

141

Dictionary with configuration from environment variables

142

143

Environment Variables:

144

- GOOGLE_ADS_DEVELOPER_TOKEN: Required developer token

145

- GOOGLE_ADS_CLIENT_ID: OAuth2 client ID

146

- GOOGLE_ADS_CLIENT_SECRET: OAuth2 client secret

147

- GOOGLE_ADS_REFRESH_TOKEN: OAuth2 refresh token

148

- GOOGLE_ADS_LOGIN_CUSTOMER_ID: Optional login customer ID

149

"""

150

151

def load_from_yaml_file(path: str = None) -> dict:

152

"""

153

Load configuration from YAML file.

154

155

Parameters:

156

- path: Path to YAML file (defaults to ./google-ads.yaml)

157

158

Returns:

159

Dictionary with configuration from YAML file

160

161

Raises:

162

- FileNotFoundError: If file doesn't exist

163

- IOError: If file can't be read

164

"""

165

166

def load_from_dict(config_dict: dict) -> dict:

167

"""

168

Load configuration from dictionary with validation.

169

170

Parameters:

171

- config_dict: Configuration dictionary

172

173

Returns:

174

Validated configuration dictionary

175

176

Raises:

177

- ValueError: If required keys are missing

178

"""

179

180

def parse_yaml_document_to_dict(yaml_str: str) -> dict:

181

"""

182

Parse YAML string to configuration dictionary.

183

184

Parameters:

185

- yaml_str: YAML configuration string

186

187

Returns:

188

Configuration dictionary

189

190

Raises:

191

- ValueError: If YAML is invalid

192

"""

193

```

194

195

### OAuth2 Authentication

196

197

OAuth2 credential management for different authentication flows.

198

199

```python { .api }

200

# OAuth2 functions

201

def get_credentials(config_data: dict) -> object:

202

"""

203

Get OAuth2 credentials from configuration data.

204

205

Parameters:

206

- config_data: Configuration dictionary

207

208

Returns:

209

Google OAuth2 credentials object

210

211

Raises:

212

- ValueError: If required authentication fields are missing

213

"""

214

215

def get_installed_app_credentials(

216

client_id: str,

217

client_secret: str,

218

refresh_token: str,

219

http_proxy: str = None,

220

token_uri: str = None

221

) -> object:

222

"""

223

Get credentials using installed application OAuth2 flow.

224

225

Parameters:

226

- client_id: OAuth2 client_id from configuration

227

- client_secret: OAuth2 client_secret from configuration

228

- refresh_token: OAuth2 refresh_token from configuration

229

- http_proxy: Optional HTTP proxy URI

230

- token_uri: Optional custom token URI

231

232

Returns:

233

OAuth2 credentials for installed app flow

234

"""

235

236

def get_service_account_credentials(

237

json_key_file_path: str,

238

subject: str,

239

http_proxy: str = None,

240

scopes: list = None

241

) -> object:

242

"""

243

Get credentials using service account authentication.

244

245

Parameters:

246

- json_key_file_path: Path to the private key file

247

- subject: Email address of the delegated account

248

- http_proxy: Optional HTTP proxy URI

249

- scopes: List of additional scopes

250

251

Returns:

252

OAuth2 credentials for service account flow

253

"""

254

```

255

256

### Usage Examples

257

258

#### Basic Client Setup from YAML

259

260

```python

261

from google.ads.googleads.client import GoogleAdsClient

262

263

# Create google-ads.yaml file with configuration

264

yaml_content = """

265

developer_token: "your_developer_token_here"

266

client_id: "your_client_id_here.apps.googleusercontent.com"

267

client_secret: "your_client_secret_here"

268

refresh_token: "your_refresh_token_here"

269

login_customer_id: "1234567890"

270

"""

271

272

# Initialize client

273

client = GoogleAdsClient.load_from_storage("google-ads.yaml")

274

275

# Access services

276

campaign_service = client.get_service("CampaignService")

277

googleads_service = client.get_service("GoogleAdsService")

278

```

279

280

#### Environment Variable Setup

281

282

```python

283

import os

284

from google.ads.googleads.client import GoogleAdsClient

285

286

# Set environment variables

287

os.environ['GOOGLE_ADS_DEVELOPER_TOKEN'] = 'your_developer_token'

288

os.environ['GOOGLE_ADS_CLIENT_ID'] = 'your_client_id.apps.googleusercontent.com'

289

os.environ['GOOGLE_ADS_CLIENT_SECRET'] = 'your_client_secret'

290

os.environ['GOOGLE_ADS_REFRESH_TOKEN'] = 'your_refresh_token'

291

os.environ['GOOGLE_ADS_LOGIN_CUSTOMER_ID'] = '1234567890'

292

293

# Initialize client from environment

294

client = GoogleAdsClient.load_from_env()

295

```

296

297

#### Service Account Authentication

298

299

```python

300

from google.ads.googleads.client import GoogleAdsClient

301

302

# Configuration with service account

303

config = {

304

'developer_token': 'your_developer_token',

305

'service_account_key_file': '/path/to/service-account.json',

306

'login_customer_id': '1234567890'

307

}

308

309

client = GoogleAdsClient.load_from_dict(config)

310

```

311

312

#### Custom Client Initialization

313

314

```python

315

from google.ads.googleads.client import GoogleAdsClient

316

from google.ads.googleads import oauth2

317

318

# Manual credential setup

319

credentials = oauth2.get_installed_app_credentials(

320

client_id='your_client_id.apps.googleusercontent.com',

321

client_secret='your_client_secret',

322

refresh_token='your_refresh_token'

323

)

324

325

# Initialize with custom settings

326

client = GoogleAdsClient(

327

credentials=credentials,

328

developer_token='your_developer_token',

329

login_customer_id='1234567890',

330

version='v21',

331

use_proto_plus=True

332

)

333

```

334

335

## Configuration Keys

336

337

### Required Keys

338

339

```python { .api }

340

REQUIRED_KEYS = {

341

'developer_token', # Google Ads developer token

342

}

343

344

# OAuth2 Installed App Flow

345

REQUIRED_INSTALLED_APP_KEYS = {

346

'client_id', # OAuth2 client ID

347

'client_secret', # OAuth2 client secret

348

'refresh_token' # OAuth2 refresh token

349

}

350

351

# Service Account Flow

352

REQUIRED_SERVICE_ACCOUNT_KEYS = {

353

'service_account_key_file', # Path to service account JSON

354

# OR

355

'service_account_key_data' # Service account JSON as string

356

}

357

```

358

359

### Optional Keys

360

361

```python { .api }

362

OPTIONAL_KEYS = {

363

'login_customer_id', # Login customer ID

364

'linked_customer_id', # Linked customer ID

365

'endpoint', # Alternative API endpoint

366

'http_proxy', # HTTP proxy URI

367

'use_proto_plus', # Use proto-plus messages

368

'use_cloud_org_for_api_access', # Use cloud org access

369

'logging' # Logging configuration

370

}

371

```

372

373

## Constants

374

375

```python { .api }

376

# OAuth2 scope for Google Ads API

377

GOOGLE_ADS_SCOPE = "https://www.googleapis.com/auth/adwords"

378

379

# Valid API versions

380

VALID_API_VERSIONS = ["v21", "v20", "v19"]

381

382

# Default API version

383

DEFAULT_VERSION = "v21"

384

```