In my previous post “How to setup Google Firebase Cloud Firestore Database“, I introduced Google Firebase Cloud Firestore where you can create a NoSQL type database. In this post, I will share with you how you can access to your Firestore database.
Table of Contents
Useful NoSQL Books
If you want to learn more about NoSQL database, check out the books below.
Python Package
You need the following package to work with Firebase Cloud Firestore.
- firebase_admin
If you do not have firebase_admin
Python package, you can install it by issuing the below command in your system or in the virtualenv
. (See “How to use VirtualEnv in Python” post for more detail how to setup and use VirtualEnv.)
pip install firebase-admin
Firebase Project and Private Key
Assuming you have followed the “How to setup Google Firebase Cloud Firestore Database” and you have the project setup, as well as you have generated the private key, once you have the private key (.JSON file), remember the path to that file or put the file as same directory as where your Python file will be. Let’s jump straight into Python coding.
Access to Firebase from Python
Import firebase-admin
First thing you need to do is, import the firebase-admin in your Python code so you can start using the modules in this package. Import the below in your Python code.
import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore
Initialize your Firebase Credentials
Next is, you need to initialize and establish your Firebase credential.
# Use a service account
cred = credentials.Certificate('serviceAccountKey.json')
firebase_admin.initialize_app(cred)
By now, you should be able to access to your Cloud Firestore database. Next is to point to the Collection
.
Loading Collection
and Document
db = firestore.client()
cars_ref = db.collection(u'cars')
docs = cars_ref.stream()
With the code above, it accessed to collection name called “cars
“.
Next is to check what’s in the cars, get it and put in the Python list.
cars_list = []
for doc in docs:
cars_list.append(doc.to_dict())
# print(u'{} => {}'.format(doc.id, doc.to_dict()))
Output the List
Finally, print the cars_list to see what’s in the list.
print(cars_list)
This should return something like below: (assuming you have those data in the Cloud Firestore database)
[{'brand': 'honda', 'model': 'civic', 'type': 'sedan'}, {'brand': 'honda', 'model': 'crv', 'type': 'suv'}]
You want to learn more about Python and NoSQL? Check out the below books
Sample Code
Cloud Firestore Official Document Reference
https://firebase.google.com/docs/firestore/quickstart?authuser=0
Latest Posts
- How to convert MD (markdown) file to PDF using Pandoc on macOS Ventura 13
- How to make MD (markdown) document
- How to Install Docker Desktop on mac M1 chip (Apple chip) macOS 12 Monterey
- How to install MySQL Workbench on macOS 12 Monterey mac M1 (2021)
- How to install MySQL Community Server on macOS 12 Monterey (2021)