iceiscold
iceiscold

Reputation: 113

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".

Upvotes: 3

Views: 1095

Answers (1)

ErnestoC
ErnestoC

Reputation: 2904

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.

Upvotes: 2

Related Questions