Reading data from Firebase database using Python script

In this article, we are going to discuss how we can read data from a Firebase database using Python. This article is the second part of the tutorial of Setting up Firebase with Python. You can find the pre-requisites for this article in the tutorial given below:

Connecting Firebase with Python

Next tutorial: How to store and Delete data to Firebase database using Python

Firebase Data Model

Before trying to perform data transactions with the Firebase DB using a python script, we will first understand the organization of data in a Firebase DB. Unlike most other Relational Databases that use tables to store and organize data, Firebase uses the notion of documents and collections. in firebase we have collections consisting of documents, where each document is nothing but a set of key-value pairs. We show the data organization of firebase in the following diagram:

Firebase Data Model

The actual Firebase database interface is as follows:

Firebase database interface

Firebase documents can also contain a sub collection as shown in the first figure.

Reading contents of the firebase database using Python

import firebase_admin
from firebase_admin import credentials,firestore

cd = credentials.Certificate("<path_to_generated_private_key>.json")

# In the above line <path_to_generated_private_key>
# is a placeholder for the generate JSON file containing
# your private key.

firebase_admin.initialize_app(cd)

datab = firestore.client()

usersref = datab.collection(u'users')
docs = usersref.stream()

for doc in docs:
    print('{} : {}'.format(doc.id,doc.to_dict()))

In the above example, ‘usersref‘ is a reference to the ‘Users‘ collection, which is the root collection. The ‘stream()‘ method creates a generator called ‘docs‘ used to access the individual documents of the collection.

When we run the above code, we get the following output:

Reading data from Firebase database using Python script

For more information about how to write data to the database, go to the next article in this series Setting up Firebase with Python.

Leave a Reply

Your email address will not be published. Required fields are marked *