Google Cloud Service Usage

1.16.0 · active · verified Thu Apr 16

The `google-cloud-service-usage` library provides a Python client for the Google Cloud Service Usage API. It enables programmatic management of Google Cloud services within your projects, including listing available services, checking their status, and enabling or disabling them. Part of the `google-cloud-python` monorepo, it is currently at version 1.16.0. Releases for this library, like others in the monorepo, occur frequently, often several times a month, reflecting updates to the underlying API or client code.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the `ServiceUsageClient` and list all enabled Google Cloud services for a specified project. Ensure your `GOOGLE_CLOUD_PROJECT` environment variable is set or replace the placeholder project ID, and that your environment is authenticated to Google Cloud.

import os
from google.cloud import service_usage_v1

# Set your Google Cloud Project ID
project_id = os.environ.get("GOOGLE_CLOUD_PROJECT", "your-gcp-project-id") # Replace with a valid project ID

# IMPORTANT: Ensure you have authenticated to GCP.
# For local development, run `gcloud auth application-default login`.
# For service accounts, set the GOOGLE_APPLICATION_CREDENTIALS environment variable.

try:
    # Initialize the Service Usage client
    client = service_usage_v1.ServiceUsageClient()
    
    # Construct the parent resource name
    parent = f"projects/{project_id}"
    
    print(f"Listing enabled services for project: {project_id}")
    
    # Create a request to list services, filtered by enabled state
    request = service_usage_v1.ListServicesRequest(
        parent=parent,
        filter="state:ENABLED"
    )
    
    # Make the API call
    response = client.list_services(request=request)
    
    enabled_services = [service.config.name for service in response.services]
    
    if enabled_services:
        print(f"Enabled services found ({len(enabled_services)}):")
        for service_name in enabled_services[:5]: # Print first 5 for brevity
            print(f"- {service_name}")
        if len(enabled_services) > 5:
            print(f"... and {len(enabled_services) - 5} more.")
    else:
        print("No enabled services found for this project or insufficient permissions.")

except Exception as e:
    print(f"An error occurred: {e}")
    print("Please ensure:")
    print("1. Your project ID is correct.")
    print("2. You are authenticated (e.g., `gcloud auth application-default login`).")
    print("3. The authenticated principal has the 'Service Usage Consumer' IAM role or equivalent.")

view raw JSON →