Connecting to Firebase with Python

Loading

Firebase is a Backend-as-a-Service (BaaS) platform from Google that provides real-time databases, authentication, cloud storage, and more. Python can interact with Firebase using the Firebase Admin SDK or third-party libraries like Pyrebase.


1. Why Use Firebase with Python?

Real-time Database – Sync data across multiple devices instantly.
Firestore (NoSQL) – Flexible, scalable, document-based storage.
Authentication – Google, Facebook, Email, and more.
Cloud Storage – Store and retrieve user-generated content.
Cloud Functions – Automate backend operations.


2. Installing Firebase SDK for Python

To work with Firebase in Python, install the required packages:

pip install firebase-admin
pip install pyrebase4 # Alternative library for authentication & database

firebase-admin is the official SDK for backend integration.
pyrebase4 is a community-supported Firebase wrapper for Python.


3. Setting Up Firebase in Google Console

Step 1: Create a Firebase Project

  1. Go to Firebase Console.
  2. Click Add Project → Enter Project Name → Click Continue.
  3. Disable Google Analytics (optional) and Create Project.

Step 2: Get Firebase Credentials (Service Account JSON)

  1. In the Firebase Console, go to Project Settings.
  2. Under the Service Accounts tab, click Generate New Private Key.
  3. Download the JSON file (contains credentials for Python to connect).

Keep this JSON file secure and never share it publicly.


4. Connecting to Firebase with Python

Using Firebase Admin SDK

Initialize Firebase Connection

import firebase_admin
from firebase_admin import credentials, firestore

# Load the service account key JSON file
cred = credentials.Certificate("path/to/serviceAccountKey.json")

# Initialize Firebase app
firebase_admin.initialize_app(cred)

# Connect to Firestore Database
db = firestore.client()

print("Connected to Firebase!")

Replace "path/to/serviceAccountKey.json" with your actual JSON file path.


5. Working with Firestore Database

Adding Data to Firestore

doc_ref = db.collection("users").document("user_1")
doc_ref.set({
"name": "John Doe",
"email": "john@example.com",
"age": 25
})

print("Data added successfully!")

set() creates or updates a document in Firestore.


Reading Data from Firestore

doc = db.collection("users").document("user_1").get()

if doc.exists:
print("User Data:", doc.to_dict())
else:
print("No such document!")

to_dict() converts Firestore data into a Python dictionary.


Updating Data in Firestore

db.collection("users").document("user_1").update({
"age": 26
})

print("User updated successfully!")

update() modifies specific fields without overwriting the document.


Deleting Data from Firestore

db.collection("users").document("user_1").delete()

print("User deleted successfully!")

delete() removes a document permanently.


6. Using Firebase Authentication in Python

Initialize Pyrebase for Authentication

import pyrebase

config = {
"apiKey": "your-api-key",
"authDomain": "your-project-id.firebaseapp.com",
"databaseURL": "https://your-database-name.firebaseio.com",
"storageBucket": "your-project-id.appspot.com",
}

firebase = pyrebase.initialize_app(config)
auth = firebase.auth()

print("Firebase Authentication initialized!")

Replace "your-api-key" and other values with your Firebase Config from the console.


User Sign Up (Email & Password)

email = "user@example.com"
password = "securepassword"

user = auth.create_user_with_email_and_password(email, password)
print("User created successfully:", user)

The user’s authentication data is stored in Firebase Authentication.


User Login (Email & Password)

email = "user@example.com"
password = "securepassword"

user = auth.sign_in_with_email_and_password(email, password)
print("User logged in:", user)

The user object contains authentication tokens.


Reset Password

auth.send_password_reset_email("user@example.com")
print("Password reset email sent!")

Sends a password reset email to the user.


7. Using Firebase Realtime Database

Firebase also provides a NoSQL JSON database called Realtime Database.

Initialize Firebase Realtime Database

db = firebase.database()

Writing Data to Realtime Database

db.child("users").child("user_1").set({
"name": "Alice",
"email": "alice@example.com",
"age": 23
})

print("User added to Realtime Database!")

Reading Data from Realtime Database

user = db.child("users").child("user_1").get()
print(user.val()) # Get the value of the record

Updating Data in Realtime Database

db.child("users").child("user_1").update({"age": 24})
print("User updated!")

Deleting Data from Realtime Database

db.child("users").child("user_1").remove()
print("User deleted!")

8. Uploading Files to Firebase Storage

storage = firebase.storage()

# Upload a file
storage.child("images/profile.jpg").put("local/path/to/image.jpg")

print("File uploaded successfully!")

The file is stored in Firebase Cloud Storage.


9. Downloading Files from Firebase Storage

storage.child("images/profile.jpg").download("profile.jpg")
print("File downloaded!")

10. Deploying Firebase Functions (Optional)

Firebase allows you to run serverless functions using Cloud Functions.
To deploy, install Firebase CLI and run:

firebase deploy --only functions

Python is not natively supported in Firebase Functions, but can be used via HTTP requests.

Leave a Reply

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