How to access firebase database without having 'Realtime Database'? - python

Im trying to connect my python script to a Firebase database.
Here is the code:
import firebase_admin
from firebase_admin import credentials, db
cred = credentials.Certificate("irebase-adminsdk-ofcmd-bwd7fbcz2c.json")
firebase_admin.initialize_app(cred, {'databaseURL':'https://company.firebaseio.com/'})
ref = db.reference('/users').get()
The ERROR Im facing looks like this:
requests.exceptions.HTTPError: 404 Client Error: Not Found for url: https://company.firebaseio.com/users.json
I did a lot of research and everyone says that I have to find the right URL in the 'Realtime Database' Section. I wonder if there is any way to access the Firebase db without having realtime one enabled.

if you are looking to access the Firebase Database without having the realtime one enabled, you can try the Cloud Firestore which is a different database service provided by Firebase which doesn't require realtime database to be enabled but you may need to change the way you are accessing the data
import firebase_admin
from firebase_admin import credentials, firestore
# Initialize the Firebase Admin SDK with your service account credentials
cred = credentials.Certificate("firebase-adminsdk-that-cred-file.json")
firebase_admin.initialize_app(cred)
# Create a reference to the Firestore database
db = firestore.client()
# Read data from a specific document in the 'users' collection
doc_ref = db.collection('users').document('user1')
doc = doc_ref.get()
# Print the data from the document
print(doc.to_dict())

Related

Cannot connect to firestore firebase in Python

I created a firebaseconfig.json file with my apikey, authodomain, databaseurl, projected, storagebucket, messagingsenderid, appid and measurementid. this comes standard in the SDK setup and configuration section of the yourapps section in project setting. but when I try running my python code.
import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore
import os
print(os.getcwd())
if not firebase_admin._apps:
cred = credentials.Certificate('src/firebaseconfig.json')
default_app = firebase_admin.initialize_app(cred)
db = firestore.client()
users_ref = db.collection(u'users')
docs = users_ref.stream()
for doc in docs:
print(f'{doc.id} => {doc.to_dict()}')
I get the Error: ValueError: Invalid service account certificate. Certificate must contain a "type" field set to "service_account".
The Firebase Admin SDK requires a service account for authentication, as opposed to a configuration file with the project keys (which is primarily used for web/iOS/Android clients).
If you have not used a service account, you need to generate a key file to use within your application through the Firebase console (Settings -> Service Accounts -> Generate New Private Key).
Afterwards, you can initialize the firestore client within your code as follows (relevant doc):
import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore
# Use the json key generated from the Firebase console
cred = credentials.Certificate('path/to/serviceAccount.json')
firebase_admin.initialize_app(cred)
db = firestore.client()
Let me know if this information was useful.

Cant find my firebase real-time database when trying to import data in python

import pandas as pd
import firebase_admin
from firebase_admin import credentials, firestore
cred = credentials.Certificate("crt")
firebase_admin.initialize_app(cred,{
'databaseURL': 'url'
})
db = firestore.client()
actor_ref = db.collection('actors')
# Import data
df = pd.read_csv("./hw1_datasets/actor.csv")
tmp = df.to_dict(orient='records')
list(map(lambda x: actor_ref.add(x), tmp))
I'm running this script to import csv to my Firebase Real-time Database and it keeps saying the project does not exist or it does not contain an active Cloud Datastore or Cloud Firestore database. I created a firebase real-time database by using the same google account and I'm not sure why is it saying no database. Does Google Cloud not support Firebase's real-time database? Any help would be strongly appreicated
Your question seems to be mixing up both Firebase Realtime Database and Firestore. While you have mentioned that you are using Firebase Realtime Database your python script is for importing data into Firestore. Please note that Firestore and Firebase Realtime Database are two different Databases.
The error message you are getting suggests that the project doesn’t have a Firestore Database. So to resolve the error please go to Firebase Console and create a Database in Firestore. After creating the Firestore database add a collection named ‘actors’. You can follow the steps mentioned here to create a Firestore database in Firebase Console.
If you want to use Firebase Realtime database you have to initialize it in the python script differently. You may look at the following as a reference to know how to initialize Firebase Realtime Database.
First you have to import ‘db’ from firebase_admin as follows
from firebase_admin import db
Then you have to create a credentials object by taking the serviceAccountKey.json file which you can generate in the Project Overview > Project Settings page in Firebase console
cred = credentials.Certificate('path/to/serviceAccountKey.json')
Next you have to initialize the database as follows -
firebase_admin.initialize_app(cred, {
'databaseURL': 'https://databaseName.firebaseio.com'
})
Now to access the Firebase Realtime Database you have to create a reference as follows
ref = db.reference('databaseName')
More details on how to initialize Firebase Realtime Database is here.
To read and save data to the Firebase Realtime Database you may refer to this document and this document respectively.
The problem is in:
firebase_admin.initialize_app(cred,{
'databaseURL': 'url'
})
The databaseURL is a reference to the Realtime Database, and it seems that is not enough for your code to find the Firestore database of the project. As shown in the documentation on setting up Python access to Firestore, you will (also) need to pass the project ID before you can access Firestore:
firebase_admin.initialize_app(cred, {
'projectId': project_id,
})
db = firestore.client()

Firebase Admin SDK: list_users() error INSUFFICIENT_PERMISSION

I'm using the Firebase Admin Python SDK to connect to our Firebase instance where are users are stored for a web application. I am attempting to create a job that queries Firebase every day and gets a count of users and then archives this off to our data warehouse to report on it going forward. I've successfully created service account credentials and made sure the credentials are valid by accessing the Google Cloud Platform (following these instructions):
import firebase_admin
creds = firebase_admin.credentials.Certificate("/Users/me/Downloads/service-account-146c01507e2b.json")
default_app = firebase_admin.initialize_app(creds)
However, the instructions are not clear on how I go about authenticating in order to pull back a list of all users. It just says to import the auth class and then run auth.list_users() but doesn't clarify how to authenticate using this class.
When I run firebase_admin.auth.list_users() I get the following error: InvalidArgumentError: Error while calling Auth service (INSUFFICIENT_PERMISSION).
Can anyone help me understand how/where I authenticate with my service account credentials? Thanks!
Firebase Service Account
The Firebase service account should be generated from:
Firebase Console > Project Settings > Service Accounts and clicking Generate new private key
Initialize Firebase SDK
import json
import firebase_admin
from firebase_admin import credentials
FIREBASE_CERT = "credentials/firebase-adminsdk-####-##########.json"
with open(FIREBASE_CERT) as json_file:
json_data = json.load(json_file)
DEFAULT_CRED = credentials.Certificate(json_data)
app_instance = firebase_admin.initialize_app(DEFAULT_CRED)
firebase_admin.auth.list_users()

Python REST API gives Internal Server Error

I'm trying to create a REST API in python .. I have decent experience in python but relatively new to REST APIs ... When I run my python script I get a "Internal Server Error" on my browser ..
Some thing like this:
Error on the browser
and on my console I see this:
Error as displayed on my console
Here's my code:
from flask import Flask, request
from flask_restful import Resource, Api
import firebase_admin
# For connecting to firestore database and authentication
from firebase_admin import credentials, firestore
# For Data base Connectivity
from firebase_admin import db
from flask import jsonify
app = Flask(__name__)
api = Api(app)
class Firebase_Data(Resource):
def getData(self):
# Setting up credentials to connect
cred = credentials.Certificate(../Path)
# Setting up secure connection to firestore Real time database
app = firebase_admin.initialize_app(cred, {
'projectId' : 'project_ID'
})
# Connecting to the firestore client
db_ref = firestore.client()
# Referring to the '** section of the data
ref_inc = db_ref.collection(u'name of column')
# Fetching all the records under that particular section and
converting them to list of dictionaries
docs = list( ref_inc.get() )
lat_long = []
for doc in docs:
data = doc.to_dict()
lat_long.append(
{ 'Latitude:' : data['latitude'], 'Longitude' :
data['longitude'] } )
return jsonify(lat_long)
api.add_resource(Firebase_Data, '/Firebase_Data') # Route_1
if __name__ == '__main__':
app.run(port=5002)
I'm basically trying to fetch some data from a Fire store database and display it on the browser. I don't think the fire store part has anything to do with my error, I think I'm missing something on executing the "get" function of my python class which I'm not able to figure out .. Any help is highly appreciated.. Thanks in advance

Connecting aws backend to firebase database

I'm currently running python code in my aws server and trying to connect to my friend's firebase database. I read the documentation provided by firebase to connect to aws server.
https://firebase.google.com/docs/admin/setup
I have followed every step but I'm getting an error when I try to connect to my server. I have added google-service.json for credential.
Error that I get :
ValueError: Invalid service account certificate. Certificate must
contain a "type" field set to "service_account".
Do I need to modify the google-services.json ?
My code:
import firebase_admin
from firebase_admin import credentials
cred = credentials.Certificate('/home/ec2-user/google-services.json')
#default_app = firebase_admin.initialize_app(cred)
other_app = firebase_admin.initialize_app(cred, name='other')
ault_app = firebase_admin.initialize_app()
google-services.json is typically the name of an Android app configuration file. That's not the same as a service account. To get a hold of the credentials for a service account for your project, you'll need to generate one from the Firebase console from Project Settings -> Service Accounts. The documentation is here. Once you have this file, you can initialize the Admin SDK with it to begin accessing the data in your project.
Better way would be to store credentials on s3 (encrypted) with a IAM role attached to lambda function.
import os
import firebase_admin
from firebase_admin import credentials
import boto3
from settings.local_settings import AWS_REGION, ENVIRONMENT
import json
firebase_config_file = 'app-admin-config-{}.json'.format(ENVIRONMENT)
firebase_admin_creds_file = 'app-admin-sdk-{}.json'.format(ENVIRONMENT)
current_dir = os.path.abspath(os.path.dirname(__file__))
files = [f for f in os.listdir(current_dir) if os.path.isfile(f)]
if firebase_config_file not in files and firebase_admin_creds_file not in files:
s3 = boto3.resource('s3', region_name=AWS_REGION)
bucket = s3.Bucket('app-s3-secrets')
firebase_config = json.loads(
bucket.Object('app-admin-config-{}.json'.format(ENVIRONMENT)).get()['Body'].read())
firebase_admin_creds = json.loads(
bucket.Object('app-admin-sdk-{}.json'.format(ENVIRONMENT)).get()['Body'].read().decode())
class Firebase:
#staticmethod
def get_connection():
cred = credentials.Certificate(firebase_admin_creds)
return firebase_admin.initialize_app(cred, firebase_config)
app = Firebase.get_connection()

Categories