Connecting Firebase with Python
In this article, we will learn how we can connect a firebase database with a Python script. This article is the first part of the tutorial series of Setting up Firebase with Python. Firebase is a NoSQL based database designed by google which is capable of providing realtime updates to android devices connected to it. We will require the following python packages:
In addition to installing the firebase-admin SDK for python using the above package, we also need to create a new Firebase database.
Creating a Firebase database for our Python program
The first thing we need to do is to sign up for a google cloud account. You can do this using an existing Google account. Then navigate to the homepage of the Google Cloud Console. It looks as follows:
Next, create a new Google Cloud Project:
To do this select the drop-down menu beside the Smart Card System in the above image. You will be shown with a box as shown below, click NEW PROJECT. A new window asking the project name will pop up. Let’s say our project name is ‘My Third Project‘ as shown below:
Once this is done create a new Firebase database as shown below:
Then select database mode. We will choose the native mode for our project.
Select a database location:
After performing the above steps our database will be created:
Once, we reach the above window, we are ready to start with the next section of the article where we link our database with a python script.
Use Firebase with Python
- We navigate to console.firebase.google.com.
- Click on ADD PROJECT and select the GCP (Google Cloud Platform) project we just created. In our case, it would be ‘My Third Project‘.
- Open ‘My Third Project’ and choose the ‘GEAR‘ icon beside ‘project overview’ and go to ‘project settings’.
- Then go to the ‘service accounts’ tab, select python and then click on the ‘Generate new private key button‘.
- NOTE: THIS STEP IS GOING TO GENERATE A PRIVATE KEY, USED TO ACCESS YOUR DATABASE. YOU HAVE TO KEEP THIS KEY CONFIDENTIAL AT ALL TIMES, BECAUSE ANYONE HAVING THIS PRIVATE KEY WILL BE ABLE TO MODIFY YOUR DATABASE. Click on ‘Generate key‘. This step will download a JSON file containing your private key. For security reasons, never add this file to any version control system.
import firebase_admin from firebase_admin import credentials 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)
Once, the above steps are done, and the above-given code executes without any errors, then you have successfully connected your python script to the Firebase DB. We will look at how we can read and write to the database in another article – Reading data from Firebase database using Python script