Using Google Cloud APIs with Python
Google Cloud Platform (GCP) provides powerful APIs that allow you to manage and interact with its services programmatically. Python is one of the most popular languages for this, thanks to the comprehensive Google Cloud Client Libraries.
Prerequisites
Before you start, ensure you have the following:
- Python 3.7+ installed on your machine
- A Google Cloud Project with billing enabled
- The gcloud CLI installed and initialized (optional)
Official Link
https://docs.cloud.google.com/sdk/docs/install-sdk
Setting Up Virtual Environment
It is highly recommended to use a virtual environment to isolate your project dependencies.
Bash
# Create a virtual environment python -m venv gcp-env # Activate it (Windows) .\gcp-env\Scripts\activate # Activate it (macOS/Linux) source gcp-env/bin/activate
Installing Client Libraries
You can install the specific libraries for the services you need. For this course, we will primarily use BigQuery and Cloud Storage.
Bash
pip install google-cloud-bigquery google-cloud-storage
Authentication
The easiest way to authenticate during local development is using Application Default Credentials (ADC).
Bash
gcloud auth application-default login
This command opens a browser to log in to your Google account. Once authenticated, the client libraries will automatically find your credentials.
Basic Example: Listing Buckets
Here is a simple script to verify your setup by listing all buckets in your project.
Python
from google.cloud import storage
def list_buckets():
# Initialize the storage client
# Automatically uses credentials from ADC
storage_client = storage.Client()
# Retrieve buckets
buckets = list(storage_client.list_buckets())
if not buckets:
print("No buckets found.")
else:
for bucket in buckets:
print(f"Bucket Name: {bucket.name}")
if __name__ == "__main__":
list_buckets() Note: Ensure the Cloud Storage API is enabled in your Google Cloud Console for the project you are using.