Connecting Your Python Project to Firebase: A Step-by-Step Guide

ยท

2 min read

There could be a lot of reasons why you'd want to connect an underlying python project to your Firebase.

In my case, I generally use it for quick testing of data.

So let's see how to connect our Python scripts to our Firebase Project.

In Firebase Console:

Go to Project Settings:

Now go to service Accounts and click on Generate new private key:

From the options presented above select python. Once you click on the generate new private key:

Remember that you need to securely store the file as once the key is generated. It can't be created again.

In my scenario. I stored it in the following path:

/Users/khkr/Documents/khkr-docs/Developer/PictureMenu/firebase-keys/pm-firebase-python-key.json

Firebase Admin SDK

If you are on Mac or Linux Environment. You can install the firebase-admin-sdk using the following command: From Firebase Docs

sudo pip install firebase-admin

If you are on windows you can use the following command:

pip install firebase-admin

Testing our Python Firebase Connection

We are going to test if our firebase connection is working by adding a small document to our Firestore.

This is my current Cloud Firestore:

Now we are going to run the following python script to add a test object into our Firestore database

import firebase_admin
from firebase_admin import credentials, firestore

# Initialize the Firebase app if it hasn't been initialized yet
if not firebase_admin._apps:
        #YOU SHOULD SET THE PATH FOR YOUR OWN PRIVATE KEY
    cred = credentials.Certificate('/Users/khkr/Documents/khkr-docs/Developer/PictureMenu/firebase-keys/pm-firebase-python-key.json')
    firebase_admin.initialize_app(cred)

# Access Firestore
db = firestore.client()

# Define the data to be added
test_data = {
    'name': 'Test User',
    'timestamp': firestore.SERVER_TIMESTAMP,
    'active': True,
    'score': 100
}

# Reference to the Firestore collection
collection_ref = db.collection('python-test')

# Add data to the collection
try:
    doc_ref = collection_ref.add(test_data)
    print(f'Data added to Firestore with document ID: {doc_ref[1].id}')
except Exception as e:
    print(f'Failed to add data to Firestore: {e}')

Here is terminal output

And this is the our firestore:

And there you go. You have successfully connected your Python project to your Firebase ๐ŸŽ‰.

Did you find this article valuable?

Support Harish Kunchala by becoming a sponsor. Any amount is appreciated!

ย