Setup/Access Firestore on Cloud Functions (Python)

April 24, 2019

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, abort

import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore

PROJECT_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 jsonify
from 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:

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.