Search code examples
pythonfirebase-authenticationraspberry-pifirebase-admin

Python Firebase Admin SDK - DefaultCredentialsError


I'm having trouble setting up credentials when initializing Firebase Admin SDK for Python. Taking inspiration from here, I'm setting it up like this:

import firebase_admin
from firebase_admin import credentials, firestore

cred = credentials.Certificate('./serviceAccountKey.json')
firebase_admin.initialize_app(cred)
db = firestore.Client()

...but this results in:

raise exceptions.DefaultCredentialsError(_HELP_MESSAGE)
google.auth.exceptions.DefaultCredentialsError: Could not automatically determine credentials. Please set GOOGLE_APPLICATION_CREDENTIALS or explicitly create credentials and re-run the application.

The only way I can get this to work is to create a GOOGLE_APPLICATION_CREDENTIALS environment variable like this first:

export GOOGLE_APPLICATION_CREDENTIALS="serviceAccountKey.json"

For the path to credentials.Certificate(path), I've tried './serviceAccountKey.json', 'serviceAccountKey.json', and even an absolute path, '/home/pi/projects/serviceAccountKey.json'

I'm doing this inside of a Raspberry Pi.

How can I get the credentials to work without having to explicitly set the GOOGLE_APPLICATION_CREDENTIALS environment variable?


Solution

  • You can set your environment variable locally with environ

    import os
    >>> os.environ["GOOGLE_APPLICATION_CREDENTIALS"]
        './serviceAccountKey.json'
    

    or

    import os
    os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = './serviceAccountKey.json'