Howto write a python-based firebase https function?

Question:

I would like to call a backend function from my mobile app. However this backend function shall be written in python. This function shall be directly callable from my mobile app, it shall access firebase, do some computations and return the result (Ideally, only if the user is authenticated…). After some searching, I found that a https request might be the correct way to do this.

But how do you write an https request in python for firebase? Can anybody point me to some code-examples or an tutorial for this? I only found a tutorial on how to write http cloud functions for google cloud

Asked By: U_flow

||

Answers:

unfortunantely there’s no Python option available on firebase cloud function reference currently is only available using Javascript & Typescript. However if you still want to use Python you can use Google Cloud Function.

Basically firebase and cloud function is the same, firebase is like add-on on top of the existing Google Cloud Functions infrastructure. The truth is there’s only Cloud Functions, and to use it you have to write and deploy using gcloud or firebase CLI.

Answered By: Kelvin

The answer by Kelvin pointed me in the right direction. However the python code (as a minimal working example) could look like this:

from flask import jsonify
import firebase_admin
from firebase_admin import auth

# Initialize the app without credentials, as the function gets it from context
firebase_admin.initialize_app()


def verifyRequest(request):
    authorization = request.headers.get('Authorization')
    token = authorization.split('Bearer ')[1]
    try:
        # This will fail in every situation BUT successful authentication
        decode_token = auth.verify_id_token(id_token=token)
    except Exception as e:
        print('Authorization failed')
        print(e)
        return jsonify({
        'data': {
            'status': 'Authorization failed'
        }})

    print('Authorization suceeded')
    return jsonify({
        'data': {
            'status': 'Authorization succeeded'
        }})

note that the function auth.verify_id_token() will raise an error when the authentication failed.

you can upload this via gcloud an the following command:

gcloud functions deploy verifyRequest --runtime python37 --trigger-http --project <YourProjectID>
Answered By: U_flow