How to store and Delete data to Firebase database using Python

In this article, we will learn about storing and deleting data to Firebase database using Python. This article is the third article in the series Setting up Firebase with Python. The pre-requisites  we need are listed in the article below:

Storing data into Firebase using Python

Let’s open the Firebase console and have a look at the present state of our database. If you are following up from our previous articles, it should look as shown below:

firebase and Python

Now,  Suppose, we want to add some more document entries to our users collection as shown below:

How to store data to Firebase database using Python

If we have to manually have to open the firebase console every time we want to add new data, it will be tedious and not of much use. The following Python code autonomously performs a write operation on running:

import firebase_admin
from firebase_admin import credentials, firestore

cred = credentials.Certificate('<path_to_generated_private_key>.json')
firebase_admin.initialize_app(cred)

db = firestore.client()

doc_ref = db.collection(u'users').document(u'ID3')
doc_ref.set({
    u'first': u'Abhijeet',
    u'last': u'Choudhuri',
})

doc_ref = db.collection(u'users').document(u'ID4')
doc_ref.set({
        u'firstname': u'Auroshis',
        u'lastname': u'Ray'
})

Similarly, if we want to delete any particular document from the collection of documents, we can use the following code snippet:

# Deleting a single document.
doc_ref = db.collection(u'users').document(u'ID4')
doc_ref.delete()

# Deleting a single entry of a document.
doc_ref = db.collection(u'users').document(u'ID3')
doc_ref.update({
    u'lastname': firestore.DELETE_FIELD
})

In the above code, in the first section, we delete the entire document with the key value of ID4.

In the second half of the code, we delete a particular field of the database. Here, we delete the lastname field of the document with the key value of  ID3. Finally, to view, how the modified database looks like, we can use the following section of code:

# Print the database contents on screen.
usersref = db.collection(u'users')
docs = usersref.stream()
for d in docs:
    print("{} : {}".format(d.id,d.to_dict()))

We get the following output:

delete any particular document from the collection of documents in firebase python

This ends the series of articles on Setting up Firebase with Python.

One response to “How to store and Delete data to Firebase database using Python”

  1. cuzureau says:

    Very nice article ! Thanks a lot 🙂
    Do you know where I can find the ‘.json’
    What does it look like ?

Leave a Reply

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