Setup/Access Firestore on Cloud Functions (Python)

What is Firestore and why use Firestore

Enable Firestore

Setup Google Cloud Functions Using Python

via firebase_admin

Add firebase-admin to requirements.txt.

# https://pypi.org/project/firebase-admin/
firebase-admin==2.16.0

Code

from flask import jsonify, abortimport firebase_adminfrom firebase_admin import credentialsfrom firebase_admin import firestorePROJECT_ID = ...cred = credentials.ApplicationDefault()default_app = firebase_admin.initialize_app(cred, {  'projectId': PROJECT_ID,})db = firestore.client()def test_firestore(request):    doc_ref = db.collection('COLLECTION').document('DOCUMENT_ID')    doc = doc_ref.get()    if doc.exists:        return jsonify(doc.to_dict())    else:        doc_ref.set({'name': 'Hello'})        return 'UPDATED'

NOTE: TypeError exception is raised by jsonify when some data is not JSON serializable (e.g. DocumentReference)

via google-cloud-firestore

Add google-cloud-firestore to requirements.txt.

# https://pypi.org/project/google-cloud-firestore/
google-cloud-firestore==1.3.0

Code

from flask import jsonifyfrom google.cloud import firestore# db = firestore.Client.from_service_account_json('PROJECT_ID-firestore.json')db = firestore.Client()def test_firestore(request):    doc_ref = db.collection('test').document('xxx')    doc = doc_ref.get()    if doc.exists:        return jsonify(doc.to_dict())    else:        doc_ref.set({'name': 'Hello'})        return 'UPDATED'

Deploy

Deploy & Test Cloud Functions

References:

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.