Firebase realtime database is a NoSQL database
that allows developers to store and synchronize data in real time. It has a simple, intuitive design and can
be easily implemented in both simple and complex applications. As pythoneers ourselves, we may need to store
and retrieve data for our python scripts and firebase can be of great help for us. Firebase provides a free tier access to its
realtime database which we can integrate with our python script using official firebase
sdk for python. So in this video, I am gonna give a step by
step guide on how you can use firebase sdk to retrieve and store data using python. If you are into python like me, you can join
our community “All about python” by subscribing on YouTube, following on Instagram or joining
our newsletter through our blog site allaboutpython.tech. So without any further ado, let’s begin Thanks to Google, setting up and getting started
with firebase is really easy. You can go to firebase website firebase.google.com
and create a new account using google sign up. Once done, you can create a new project within
firebase. Each project here can represent an application
or program which is using firebase. Once the project is created, you can go to
Build and Click on Realtime Database to get started with creating a reatime database for
you. First you need to setup the location of the
database. You can select whichever location is closest
to your location. Next you need to select the mode to use in
the database. Locked mode is used to grant access to only
certain privileged accounts, while test mode will give access to anyone who has the link
to the database. For tutorial purpose, I would suggest using
test mode. But for production environment, its secure
to use locked mode. Once the mode is selected, you can click on
“Enable” to start creating the database. It will take a few seconds to complete, but
once done, you will be able to see a screen similar to this one. The URL that you see here is our database
URL. We will be using this URL within our python
script. With this, our database is ready to work. Before we dive into writing some code, we
need to understand how a firebase realtime database actually works. Like I told you before, this database is a
NoSQL database, which means it does not involve the concept of tables, keys or relationships. Instead, it uses a JSON like structure to
store data inside it, called node. Developers can create these nodes as key value
pairs and store common data types like integer, float, string, list and dictionary objects
inside it. Each node has its own path, which represents
its location within the database. For ex: if you look at this JSON file here,
you can see we have a bunch of key value pairs. Some keys store smaller JSON files inside
it which in turn have its own keys and values.Let’s assume this data is stored in this exact format
inside firebase. The address of this whole data will be “/”, as
this whole data is present at the root of the database. If I want the path to this node, name = Vishesh,
then its address will be /name as the name of the key of this node is name. Similarly if I want the path to this node
that stores the channel URL, its path will be /channel/url as this node is stored within
this node with the key channel and the keyname of this node is url. We will use this same concept of path to navigate
across the data stored in firebase. If you have any issues understanding it, just
continue with this tutorial as you will understand as we move on to the coding part. We will start by installing the firebase sdk
package for python called firebase_admin. To install it, open command prompt and type pip install firebase_admin And hit enter. Once the package is installed, we will go
to the firebase account, and click on Settings (present beside Project Overview)
and then click on Project Settings. Next we will click on “Service Accounts”. Once the page is opened, we will click on
“Generate new private key”. This will download a json file on our system,
which we will use to authenticate to firebase. Now you can create a new folder to store the
demo code, and copy paste the json file inside the folder. For ease of use, you can rename this file
to credentials.json as I have done for this demo. Now we are ready to start with the coding
part. For this demo, I am using jupyter notebook
so that I could easily explain each and every line of code that we write. You can write the same code inside a python
file and it will work exactly the same. We will start by importing the required modules. Firstly i will import the firebase_admin module
and in the next line we will separately import db and credentials module from firebase_admin. Next, we will start by reading the json file
that we had downloaded from firebase for authentication. We will create a variable named cred and store
the object of class credentials.Certificate. We will pass the path to the json file here. Since I have created this file one the same
folder, I will just write the name of the file. Next we will call the firebase_admin.initialize_app
function. This function is necessary to call before
we perform any operation on the database. Within the function, we first pass the cred
variable which stores the credentials from json, file and then we pass a dictionary object
with key databaseURL and a url. This is our database URl which you can get
by opening the real time database on web and copying this URL from here. After writing the url, we will run this line
and we will get an App object in return. Next, we will talk about references in firebase_admin. References in firebase_admin sdk are python
classes that are used to represent nodes in firebase. Each reference object has a key, value and
a set of functions used to perform operations on that specific node. If we want to perform any operation, we have
to first get the node using the reference function and then we can perform any action
on that node. We can create a reference object by calling
db.reference function. Within the function, we can pass the path
to the node in the database. For ex: to get the root node, we will pass
“/” as a string to the function. We will also store the object returned in
a variable named ref. Now we can use this reference object variable
to perform operations on the database. The first operation we are going to talk about
is the get operation. Using this, we can retrieve data from firebase. Using this is very simple. You can use ref.key to get the name of the
key of the reference and you can use the get() function to get the value of the reference. For ex, if i use ref.key, you can see nothing
gets displayed as ref here is the root node and root node is the only node that does not
have any key name. But if we use ref.get(), you can see that
we get a dictionary object with lots of data. This is because I had already stored this
value in the database, which you can see here, and now I am able to retrieve that value from
python. If i just want to get the value of the name
key, I can mention that node by writing db.reference(“/name”) and then calling .get() function to get its
value. On running it we can see its value. The next operation we are gonna talk about
is the set operation. Using this, we can set any value inside an
existing node using its key. We will use the set function for this. The function will override any existing value
present inside the node with the new value passed onto this function. For ex: If I want to set the value of videos
key to just be 3 and not a list of numbers, i can write
db.reference(“/videos”).set(3). If i run ref.get now, we can see that the
videos key has value 3 now, and the old value of list of numbers got replaced with the new
value. The next operation is the update operation. Using this, we can update any existing node
with the new value. We will use the update function for this. Note that unlike the set operation which replaces
the node value with the new one, the update operation adds the new node to the existing
node value. If the node is already present, it will just
update its value. For ex: If i want to change the value of language
key without changing any other value, I can write db.reference(“/”).update({“language”:
“python”}) If i run ref.get now, we can see that the
language key has the value “python” and the old value of “Python” got updated
with the new value. If I want to add a new key value pair onto
the root node, I can write db.reference(“/”).update({“subscribed”:
True}) Now if I run ref.get(), we can see that a
new key value pair, subscribed equals to true has been added to the root node. The next operation is the push operation. Using this, we can add a new child node to
an existing node. We will use the push function for this. Note that when we use this operator, we also
need to use the set operator to set the new value of the new node added to the parent
node. This operation can also be used on a list
to append a new element. For ex: If I want to add a new title to the
titles node, I can write db.reference(“/titles”).push().set(“Python
Playwright Tutorial”) If I run ref.get now, we can see that the
titles key has the value “Python Playwright Tutorial” added onto the list. If your firebase realtime database is being
used by multiple clients at the same time, it could be difficult to update values for
all the clients. In order to resolve this, the concept of transactions
exist. A transaction is used when you want to change
small specific values by small increment at a time. For ex: I have created a function here which
takes in the current value of title_count in root node and increments it by one and
returns it. Then I create the root node reference and
call the transaction function and pass the newly created function inside it. Now if I run it, the code will update the
title_count everytime this line is executed. At last, we have the delete operation. As the name suggests, this operation is used
to remove a key value pair. We use the delete method to perform this operation. We call the function on the reference object
we want to delete. For ex: If i want to remove the language key
value pair from root, I will write db.reference(“/language”).delete() And if I run the ref.get() method, we can
see that the language key value pair is removed That’s all for this video, hope you liked
it. If you did, don’’t forget to like this
video and subscribe to the channel. With this, its time for me to go, this is
Vishesh Dvivedi signing off.