0
# Budget Service Clients
1
2
Client classes for interacting with the Google Cloud Billing Budgets API. Provides both synchronous and asynchronous implementations with comprehensive support for all budget operations.
3
4
## Capabilities
5
6
### Synchronous Client
7
8
The main synchronous client for budget operations with full CRUD support and built-in authentication.
9
10
```python { .api }
11
class BudgetServiceClient:
12
def __init__(
13
self,
14
credentials: Optional[Credentials] = None,
15
transport: Optional[Union[str, BudgetServiceTransport]] = None,
16
client_options: Optional[ClientOptions] = None,
17
client_info: Optional[gapic_v1.client_info.ClientInfo] = None,
18
**kwargs
19
):
20
"""
21
Initialize the Budget Service Client.
22
23
Args:
24
credentials: The authorization credentials to attach to requests
25
transport: The transport to use ('grpc', 'grpc_asyncio', 'rest')
26
client_options: Custom options for the client
27
client_info: The client info used to send user agent headers
28
"""
29
30
def create_budget(
31
self,
32
request: Optional[Union[CreateBudgetRequest, dict]] = None,
33
*,
34
parent: Optional[str] = None,
35
budget: Optional[Budget] = None,
36
retry: OptionalRetry = None,
37
timeout: Optional[float] = None,
38
metadata: Sequence[Tuple[str, str]] = ()
39
) -> Budget:
40
"""
41
Creates a budget and returns the created budget.
42
43
Args:
44
request: The request object or dict
45
parent: Required. Name of the billing account (billingAccounts/{id})
46
budget: Required. Budget to create
47
retry: Retry configuration
48
timeout: Timeout in seconds
49
metadata: Additional gRPC metadata
50
51
Returns:
52
Budget: The created budget
53
54
Raises:
55
google.api_core.exceptions.GoogleAPICallError: If the request fails
56
"""
57
58
def get_budget(
59
self,
60
request: Optional[Union[GetBudgetRequest, dict]] = None,
61
*,
62
name: Optional[str] = None,
63
retry: OptionalRetry = None,
64
timeout: Optional[float] = None,
65
metadata: Sequence[Tuple[str, str]] = ()
66
) -> Budget:
67
"""
68
Returns a budget.
69
70
Args:
71
request: The request object or dict
72
name: Required. Budget name (billingAccounts/{id}/budgets/{id})
73
retry: Retry configuration
74
timeout: Timeout in seconds
75
metadata: Additional gRPC metadata
76
77
Returns:
78
Budget: The requested budget
79
80
Raises:
81
google.api_core.exceptions.NotFound: If budget doesn't exist
82
"""
83
84
def list_budgets(
85
self,
86
request: Optional[Union[ListBudgetsRequest, dict]] = None,
87
*,
88
parent: Optional[str] = None,
89
scope: Optional[str] = None,
90
retry: OptionalRetry = None,
91
timeout: Optional[float] = None,
92
metadata: Sequence[Tuple[str, str]] = ()
93
) -> ListBudgetsPager:
94
"""
95
Returns a list of budgets for a billing account.
96
97
Args:
98
request: The request object or dict
99
parent: Required. Name of the billing account (billingAccounts/{id})
100
scope: Optional. Set to projects/{id} to list budgets for project
101
retry: Retry configuration
102
timeout: Timeout in seconds
103
metadata: Additional gRPC metadata
104
105
Returns:
106
ListBudgetsPager: Pager for iterating through results
107
108
Raises:
109
google.api_core.exceptions.GoogleAPICallError: If the request fails
110
"""
111
112
def update_budget(
113
self,
114
request: Optional[Union[UpdateBudgetRequest, dict]] = None,
115
*,
116
budget: Optional[Budget] = None,
117
update_mask: Optional[FieldMask] = None,
118
retry: OptionalRetry = None,
119
timeout: Optional[float] = None,
120
metadata: Sequence[Tuple[str, str]] = ()
121
) -> Budget:
122
"""
123
Updates a budget and returns the updated budget.
124
125
Args:
126
request: The request object or dict
127
budget: Required. Updated budget
128
update_mask: Optional. Indicates which fields to update
129
retry: Retry configuration
130
timeout: Timeout in seconds
131
metadata: Additional gRPC metadata
132
133
Returns:
134
Budget: The updated budget
135
136
Raises:
137
google.api_core.exceptions.NotFound: If budget doesn't exist
138
"""
139
140
def delete_budget(
141
self,
142
request: Optional[Union[DeleteBudgetRequest, dict]] = None,
143
*,
144
name: Optional[str] = None,
145
retry: OptionalRetry = None,
146
timeout: Optional[float] = None,
147
metadata: Sequence[Tuple[str, str]] = ()
148
) -> None:
149
"""
150
Deletes a budget.
151
152
Args:
153
request: The request object or dict
154
name: Required. Budget name (billingAccounts/{id}/budgets/{id})
155
retry: Retry configuration
156
timeout: Timeout in seconds
157
metadata: Additional gRPC metadata
158
159
Raises:
160
google.api_core.exceptions.NotFound: If budget doesn't exist
161
"""
162
```
163
164
### Asynchronous Client
165
166
Fully asynchronous client with the same API surface as the synchronous client but using async/await patterns.
167
168
```python { .api }
169
class BudgetServiceAsyncClient:
170
def __init__(
171
self,
172
credentials: Optional[Credentials] = None,
173
transport: Optional[Union[str, BudgetServiceTransport]] = None,
174
client_options: Optional[ClientOptions] = None,
175
client_info: Optional[gapic_v1.client_info.ClientInfo] = None,
176
**kwargs
177
):
178
"""Initialize the async Budget Service Client."""
179
180
async def create_budget(
181
self,
182
request: Optional[Union[CreateBudgetRequest, dict]] = None,
183
*,
184
parent: Optional[str] = None,
185
budget: Optional[Budget] = None,
186
retry: OptionalRetry = None,
187
timeout: Optional[float] = None,
188
metadata: Sequence[Tuple[str, str]] = ()
189
) -> Budget:
190
"""Async version of create_budget."""
191
192
async def get_budget(
193
self,
194
request: Optional[Union[GetBudgetRequest, dict]] = None,
195
*,
196
name: Optional[str] = None,
197
retry: OptionalRetry = None,
198
timeout: Optional[float] = None,
199
metadata: Sequence[Tuple[str, str]] = ()
200
) -> Budget:
201
"""Async version of get_budget."""
202
203
async def list_budgets(
204
self,
205
request: Optional[Union[ListBudgetsRequest, dict]] = None,
206
*,
207
parent: Optional[str] = None,
208
scope: Optional[str] = None,
209
retry: OptionalRetry = None,
210
timeout: Optional[float] = None,
211
metadata: Sequence[Tuple[str, str]] = ()
212
) -> ListBudgetsAsyncPager:
213
"""Async version of list_budgets."""
214
215
async def update_budget(
216
self,
217
request: Optional[Union[UpdateBudgetRequest, dict]] = None,
218
*,
219
budget: Optional[Budget] = None,
220
update_mask: Optional[FieldMask] = None,
221
retry: OptionalRetry = None,
222
timeout: Optional[float] = None,
223
metadata: Sequence[Tuple[str, str]] = ()
224
) -> Budget:
225
"""Async version of update_budget."""
226
227
async def delete_budget(
228
self,
229
request: Optional[Union[DeleteBudgetRequest, dict]] = None,
230
*,
231
name: Optional[str] = None,
232
retry: OptionalRetry = None,
233
timeout: Optional[float] = None,
234
metadata: Sequence[Tuple[str, str]] = ()
235
) -> None:
236
"""Async version of delete_budget."""
237
```
238
239
### Authentication and Factory Methods
240
241
Both client classes provide factory methods for authentication and path construction utilities.
242
243
```python { .api }
244
# Available on both BudgetServiceClient and BudgetServiceAsyncClient
245
@classmethod
246
def from_service_account_info(
247
cls,
248
info: dict,
249
*args,
250
**kwargs
251
) -> BudgetServiceClient:
252
"""
253
Create client from service account info dictionary.
254
255
Args:
256
info: Service account info in Google format
257
258
Returns:
259
BudgetServiceClient: Configured client instance
260
"""
261
262
@classmethod
263
def from_service_account_file(
264
cls,
265
filename: str,
266
*args,
267
**kwargs
268
) -> BudgetServiceClient:
269
"""
270
Create client from service account JSON file.
271
272
Args:
273
filename: Path to service account JSON file
274
275
Returns:
276
BudgetServiceClient: Configured client instance
277
"""
278
```
279
280
### Resource Path Helpers
281
282
Utility methods for constructing and parsing Google Cloud resource names.
283
284
```python { .api }
285
# Path construction methods
286
@staticmethod
287
def budget_path(billing_account: str, budget: str) -> str:
288
"""Return a fully-qualified budget string."""
289
290
@staticmethod
291
def parse_budget_path(path: str) -> Dict[str, str]:
292
"""Parse a budget path into its component segments."""
293
294
@staticmethod
295
def common_billing_account_path(billing_account: str) -> str:
296
"""Return a fully-qualified billing_account string."""
297
298
@staticmethod
299
def parse_common_billing_account_path(path: str) -> Dict[str, str]:
300
"""Parse a billing_account path into its component segments."""
301
302
@staticmethod
303
def common_project_path(project: str) -> str:
304
"""Return a fully-qualified project string."""
305
306
@staticmethod
307
def parse_common_project_path(path: str) -> Dict[str, str]:
308
"""Parse a project path into its component segments."""
309
310
@staticmethod
311
def common_organization_path(organization: str) -> str:
312
"""Return a fully-qualified organization string."""
313
314
@staticmethod
315
def parse_common_organization_path(path: str) -> Dict[str, str]:
316
"""Parse an organization path into its component segments."""
317
318
@staticmethod
319
def common_folder_path(folder: str) -> str:
320
"""Return a fully-qualified folder string."""
321
322
@staticmethod
323
def parse_common_folder_path(path: str) -> Dict[str, str]:
324
"""Parse a folder path into its component segments."""
325
326
@staticmethod
327
def common_location_path(project: str, location: str) -> str:
328
"""Return a fully-qualified location string."""
329
330
@staticmethod
331
def parse_common_location_path(path: str) -> Dict[str, str]:
332
"""Parse a location path into its component segments."""
333
```
334
335
### Pagination Support
336
337
Specialized pager classes for handling paginated responses from list operations.
338
339
```python { .api }
340
class ListBudgetsPager:
341
"""Synchronous pager for list_budgets results."""
342
343
def __iter__(self) -> Iterator[Budget]:
344
"""Iterate over Budget objects."""
345
346
@property
347
def pages(self) -> Iterator[ListBudgetsResponse]:
348
"""Iterate over raw response pages."""
349
350
class ListBudgetsAsyncPager:
351
"""Asynchronous pager for list_budgets results."""
352
353
def __aiter__(self) -> AsyncIterator[Budget]:
354
"""Async iterate over Budget objects."""
355
356
@property
357
def pages(self) -> AsyncIterator[ListBudgetsResponse]:
358
"""Async iterate over raw response pages."""
359
```
360
361
## Usage Examples
362
363
### Basic Client Usage
364
365
```python
366
from google.cloud.billing import budgets
367
368
# Initialize client with default credentials
369
client = budgets.BudgetServiceClient()
370
371
# Or with custom credentials
372
from google.oauth2 import service_account
373
credentials = service_account.Credentials.from_service_account_file(
374
"path/to/service-account.json"
375
)
376
client = budgets.BudgetServiceClient(credentials=credentials)
377
378
# Or from environment
379
client = budgets.BudgetServiceClient.from_service_account_file(
380
"path/to/service-account.json"
381
)
382
```
383
384
### Async Client Usage
385
386
```python
387
import asyncio
388
from google.cloud.billing import budgets
389
390
async def manage_budgets():
391
client = budgets.BudgetServiceAsyncClient()
392
393
parent = "billingAccounts/123456-ABCDEF-789012"
394
395
# List budgets asynchronously
396
async for budget in await client.list_budgets(parent=parent):
397
print(f"Budget: {budget.display_name}")
398
399
await client.close()
400
401
# Run the async function
402
asyncio.run(manage_budgets())
403
```
404
405
### Pagination Example
406
407
```python
408
from google.cloud.billing import budgets
409
410
client = budgets.BudgetServiceClient()
411
parent = "billingAccounts/123456-ABCDEF-789012"
412
413
# Iterate through all budgets
414
for budget in client.list_budgets(parent=parent):
415
print(f"Budget: {budget.display_name}")
416
417
# Or iterate through pages
418
pager = client.list_budgets(parent=parent)
419
for page in pager.pages:
420
print(f"Page has {len(page.budgets)} budgets")
421
for budget in page.budgets:
422
print(f" - {budget.display_name}")
423
```