I’m trying to build a google cloud function with a HTTP API request, but it looks like it’s not working.
What i’ve tried:
- Already double checked API key if it’s correct (API key is generated by Google cloud console)
- Check if I have all required imports
- Tried without the API and it worked
from google.cloud import firestore
import datetime
import functions_framework
@functions_framework.http
def update_visitor_count(request):
# Extract API key from query parameters
api_key = request.args.get('api_key')
# Validate API key (example: compare with a known API key)
if api_key != 'MY_API_KEY':
return 'Unauthorized', 401 # Unauthorized status code
# Initialize Firestore client
db = firestore.Client(project="MY_PROJECT_ID", database="db-test")
# Get today's date
today_date = datetime.date.today().isoformat()
# Get reference to the document for today's date
doc_ref = db.collection('visitor_stats').document(today_date)
# Get current visitor count for today
doc = doc_ref.get()
if doc.exists:
current_count = doc.to_dict().get('count', 0)
else:
current_count = 0
# Increment visitor count by 1
new_count = current_count + 1
# Update Firestore document with new count
doc_ref.set({'count': new_count})
return f'Visitor counts updated to {new_count} for {today_date}'
This was the one I was doing without API and it worked.
from google.cloud import firestore
import datetime
import functions_framework
@functions_framework.http
def update_visitor_count(request):
# Initialize Firestore client
db = firestore.Client(project="MY_PROJECT_ID", database="db-test")
# Get today's date
today_date = datetime.date.today().isoformat()
# Get reference to the document for today's date
doc_ref = db.collection('visitor_stats').document(today_date)
# Get current visitor count for today
doc = doc_ref.get()
if doc.exists:
current_count = doc.to_dict().get('count', 0)
else:
current_count = 0
# Increment visitor count by 1
new_count = current_count + 1
# Update Firestore document with new count
doc_ref.set({'count': new_count})
return f'Visitor counts updated to {new_count} for {today_date}'
Any help or direction would be much appreciated