Access Firestore From Google Cloud Functions

April 21, 2019

requirements.txt

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

main.py

from flask import jsonify
import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore
import google.cloud.exceptions

# this should solve the "The default Firebase app already exists." exception
cred = credentials.ApplicationDefault()
default_app = firebase_admin.initialize_app(cred, {
  'projectId': '...',
})
db = firestore.client()

def test_firestore(request):
    doc_ref = db.collection('test').document('5pSFOxspzl75hYZzjnut')

    try:
        doc = doc_ref.get()
        data = doc.to_dict()
        return jsonify(data)
    except google.cloud.exceptions.NotFound:
        return 'Not found'
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.