On this page
article
Google Cloud Functions with Python
Build and deploy Python functions on Google Cloud Functions — HTTP triggers, background events, and Firebase integration.
Google Cloud Functions (GCF) runs Python code in response to HTTP requests and Google Cloud events. It integrates tightly with Firebase, Pub/Sub, and Cloud Storage.
Your First Function
# main.py
import functions_framework
@functions_framework.http
def hello_http(request):
name = request.args.get('name', 'World')
return f'Hello, {name}!'
Deploy
pip install functions-framework
# Local testing
functions-framework --target=hello_http --debug
# Deploy to GCP
gcloud functions deploy hello-http \
--gen2 \
--runtime=python312 \
--region=us-central1 \
--source=. \
--entry-point=hello_http \
--trigger-http \
--allow-unauthenticated
JSON API Function
import functions_framework
import json
@functions_framework.http
def api_handler(request):
if request.method == 'GET':
return json.dumps([{'id': 1, 'name': 'Item'}]), 200, {'Content-Type': 'application/json'}
if request.method == 'POST':
data = request.get_json()
return json.dumps({'id': 2, 'name': data['name']}), 201, {'Content-Type': 'application/json'}
return json.dumps({'error': 'Method not allowed'}), 405
Background Event Triggers
Process Cloud Storage uploads:
import functions_framework
@functions_framework.cloud_event
def process_upload(cloud_event):
data = cloud_event.data
bucket = data["bucket"]
name = data["name"]
print(f"Processing gs://{bucket}/{name}")
# Download and process the file...
Deploy with a storage trigger:
gcloud functions deploy process-upload \
--gen2 \
--runtime=python312 \
--region=us-central1 \
--source=. \
--entry-point=process_upload \
--trigger-event-filters="type=google.cloud.storage.object.v1.finalized" \
--trigger-event-filters="bucket=my-bucket"
Pub/Sub Trigger
@functions_framework.cloud_event
def pubsub_handler(cloud_event):
import base64
message = base64.b64decode(cloud_event.data["message"]["data"]).decode()
print(f"Received message: {message}")
Requirements
Create requirements.txt for dependencies:
functions-framework==3.*
requests==2.31.0
google-cloud-storage==2.*
Cloud Functions automatically installs dependencies during deployment.
Firebase Integration
Cloud Functions integrate with Firebase for mobile/web backends:
from firebase_functions import https_fn
@https_fn.on_request()
def hello_firebase(req: https_fn.Request) -> https_fn.Response:
return https_fn.Response("Hello from Firebase!")
Deploy with Firebase CLI:
firebase deploy --only functions
Best Practices
- Use Gen 2 functions for better performance and CloudEvent support
- Set memory and timeout appropriately in deployment config
- Use Secret Manager for sensitive configuration
- Enable Cloud Logging for debugging and monitoring
- Keep cold start times low — minimize dependencies
Google Cloud Functions excels when your stack is already on GCP or Firebase.