Google Cloud Billing Budgets API client library for creating and managing cloud billing budgets
—
API request and response message types for all budget operations, including specialized pagination response handling and field mask support for partial updates.
Request and response types for creating new budgets.
class CreateBudgetRequest:
"""
Request message for creating a budget.
Attributes:
parent (str): Required. Name of the billing account to create budget in.
Format: billingAccounts/{billingAccountId}
budget (Budget): Required. Budget to create
"""
parent: str # Format: billingAccounts/{billingAccountId}
budget: Budget
# Response: Budget object (the created budget)Request type for retrieving a specific budget by name.
class GetBudgetRequest:
"""
Request message for getting a budget.
Attributes:
name (str): Required. Name of budget to retrieve.
Format: billingAccounts/{billingAccountId}/budgets/{budgetId}
"""
name: str # Format: billingAccounts/{billingAccountId}/budgets/{budgetId}
# Response: Budget objectRequest type for updating existing budgets with optional field masking for partial updates.
class UpdateBudgetRequest:
"""
Request message for updating a budget.
Attributes:
budget (Budget): Required. The updated budget object. Must contain
a valid name field for identifying the budget to update
update_mask (FieldMask): Optional. Indicates which budget fields
should be updated. If not provided, all fields will be updated
"""
budget: Budget
update_mask: FieldMask
# Response: Budget object (the updated budget)Request type for deleting budgets.
class DeleteBudgetRequest:
"""
Request message for deleting a budget.
Attributes:
name (str): Required. Name of the budget to delete.
Format: billingAccounts/{billingAccountId}/budgets/{budgetId}
"""
name: str # Format: billingAccounts/{billingAccountId}/budgets/{budgetId}
# Response: Empty (no content returned on successful deletion)Request and response types for listing budgets with pagination support and optional project scoping.
class ListBudgetsRequest:
"""
Request message for listing budgets.
Attributes:
parent (str): Required. Name of billing account to list budgets for.
Format: billingAccounts/{billingAccountId}
scope (str): Optional. Set to projects/{projectId} to list budgets
that are scoped to a specific project
page_size (int): Optional. Requested page size. Maximum value is 100.
If not specified, returns at most 50 budgets
page_token (str): Optional. Page token for pagination. Pass the
next_page_token from previous response to get next page
"""
parent: str # Format: billingAccounts/{billingAccountId}
scope: str # Optional: projects/{projectId}
page_size: int # Max 100, default ~50
page_token: str
class ListBudgetsResponse:
"""
Response message for listing budgets.
Attributes:
budgets (List[Budget]): List of budgets owned by the specified
billing account
next_page_token (str): Token to retrieve the next page of results.
Empty if no more results exist
"""
budgets: List[Budget]
next_page_token: str
@property
def raw_page(self) -> ListBudgetsResponse:
"""
Returns the raw page response (self).
Required for pager compatibility.
"""
return selfSupporting types used in request and response messages.
class FieldMask:
"""
A field mask to specify which fields should be updated.
Attributes:
paths (List[str]): The set of field mask paths. Examples:
- ["display_name"] - Update only display name
- ["amount", "threshold_rules"] - Update amount and thresholds
- ["budget_filter.projects"] - Update only filter projects
"""
paths: List[str]from google.cloud.billing import budgets
# Create request object
request = budgets.CreateBudgetRequest(
parent="billingAccounts/123456-ABCDEF-789012",
budget=budgets.Budget(
display_name="Development Budget",
amount=budgets.BudgetAmount(
specified_amount={"currency_code": "USD", "units": 500}
),
budget_filter=budgets.Filter(
projects=["projects/dev-project"],
calendar_period=budgets.CalendarPeriod.MONTH
),
threshold_rules=[
budgets.ThresholdRule(
threshold_percent=0.8,
spend_basis=budgets.ThresholdRule.Basis.CURRENT_SPEND
)
]
)
)
# Send request
client = budgets.BudgetServiceClient()
created_budget = client.create_budget(request=request)
# Or use keyword arguments directly
created_budget = client.create_budget(
parent="billingAccounts/123456-ABCDEF-789012",
budget=budget
)from google.cloud.billing import budgets
# Create request object
request = budgets.GetBudgetRequest(
name="billingAccounts/123456-ABCDEF-789012/budgets/budget-id-123"
)
# Send request
client = budgets.BudgetServiceClient()
budget = client.get_budget(request=request)
# Or use keyword arguments
budget = client.get_budget(
name="billingAccounts/123456-ABCDEF-789012/budgets/budget-id-123"
)from google.cloud.billing import budgets
from google.protobuf import field_mask_pb2
# Get existing budget first
client = budgets.BudgetServiceClient()
budget_name = "billingAccounts/123456-ABCDEF-789012/budgets/budget-id-123"
existing_budget = client.get_budget(name=budget_name)
# Modify only specific fields
existing_budget.display_name = "Updated Budget Name"
existing_budget.threshold_rules = [
budgets.ThresholdRule(
threshold_percent=0.75, # Changed from 0.8 to 0.75
spend_basis=budgets.ThresholdRule.Basis.CURRENT_SPEND
)
]
# Create field mask to specify which fields to update
update_mask = field_mask_pb2.FieldMask(
paths=["display_name", "threshold_rules"]
)
# Create update request
request = budgets.UpdateBudgetRequest(
budget=existing_budget,
update_mask=update_mask
)
# Send request
updated_budget = client.update_budget(request=request)
# Or use keyword arguments
updated_budget = client.update_budget(
budget=existing_budget,
update_mask=update_mask
)from google.cloud.billing import budgets
# List all budgets for a billing account
request = budgets.ListBudgetsRequest(
parent="billingAccounts/123456-ABCDEF-789012",
page_size=10 # Get 10 budgets per page
)
client = budgets.BudgetServiceClient()
response = client.list_budgets(request=request)
# Process first page
for budget in response.budgets:
print(f"Budget: {budget.display_name}")
# Get next page if available
if response.next_page_token:
next_request = budgets.ListBudgetsRequest(
parent="billingAccounts/123456-ABCDEF-789012",
page_size=10,
page_token=response.next_page_token
)
next_response = client.list_budgets(request=next_request)
# Or use the pager (recommended)
pager = client.list_budgets(
parent="billingAccounts/123456-ABCDEF-789012"
)
# Iterate through all budgets automatically
for budget in pager:
print(f"Budget: {budget.display_name}")from google.cloud.billing import budgets
# List budgets scoped to a specific project
request = budgets.ListBudgetsRequest(
parent="billingAccounts/123456-ABCDEF-789012",
scope="projects/my-specific-project"
)
client = budgets.BudgetServiceClient()
response = client.list_budgets(request=request)
print(f"Found {len(response.budgets)} budgets for the project")
for budget in response.budgets:
print(f"Project Budget: {budget.display_name}")from google.cloud.billing import budgets
# Create delete request
request = budgets.DeleteBudgetRequest(
name="billingAccounts/123456-ABCDEF-789012/budgets/budget-id-123"
)
# Send request (no response content on success)
client = budgets.BudgetServiceClient()
client.delete_budget(request=request)
# Or use keyword arguments
client.delete_budget(
name="billingAccounts/123456-ABCDEF-789012/budgets/budget-id-123"
)
print("Budget deleted successfully")from google.cloud.billing import budgets
client = budgets.BudgetServiceClient()
parent = "billingAccounts/123456-ABCDEF-789012"
# Create multiple budgets
budgets_to_create = [
budgets.Budget(
display_name=f"Project {i} Budget",
amount=budgets.BudgetAmount(
specified_amount={"currency_code": "USD", "units": 1000 * (i + 1)}
),
budget_filter=budgets.Filter(
projects=[f"projects/project-{i}"],
calendar_period=budgets.CalendarPeriod.MONTH
)
)
for i in range(3)
]
created_budgets = []
for budget in budgets_to_create:
created_budget = client.create_budget(parent=parent, budget=budget)
created_budgets.append(created_budget)
print(f"Created: {created_budget.name}")
# List all budgets to verify
pager = client.list_budgets(parent=parent)
all_budgets = list(pager)
print(f"Total budgets: {len(all_budgets)}")
# Clean up - delete created budgets
for budget in created_budgets:
client.delete_budget(name=budget.name)
print(f"Deleted: {budget.name}")Common error scenarios and their handling:
from google.cloud.billing import budgets
from google.api_core import exceptions
client = budgets.BudgetServiceClient()
try:
# Attempt to get a non-existent budget
budget = client.get_budget(
name="billingAccounts/123456/budgets/non-existent"
)
except exceptions.NotFound:
print("Budget not found")
except exceptions.PermissionDenied:
print("Insufficient permissions to access budget")
except exceptions.InvalidArgument as e:
print(f"Invalid request: {e}")
except exceptions.GoogleAPICallError as e:
print(f"API call failed: {e}")
try:
# Attempt to create budget with invalid parent
client.create_budget(
parent="invalid-parent-format",
budget=budgets.Budget(display_name="Test")
)
except exceptions.InvalidArgument as e:
print(f"Invalid parent format: {e}")Install with Tessl CLI
npx tessl i tessl/pypi-google-cloud-billing-budgets